github.com/enetx/g@v1.0.80/examples/files/file_guard.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "time" 6 7 "github.com/enetx/g" 8 ) 9 10 func main() { 11 // Create a channel to signal the main goroutine when the other goroutine completes 12 exit := make(chan struct{}) 13 14 // Specify the file name 15 fname := g.String("test_file.txt") 16 17 // Create and guard the file 18 f := g.NewFile(fname).Guard() 19 20 // Append data to the original file 21 f.Append("test string") 22 23 // Goroutine to read and print from the file 24 go func() { 25 fmt.Println("Waiting for guard release") 26 // Create a new file and guard it for reading 27 g.NewFile(fname).Guard().Read().Unwrap().Print() 28 // Signal the main goroutine that the reading is complete 29 exit <- struct{}{} 30 }() 31 32 // Goroutine to release the guard after 2 seconds 33 go func() { 34 // Sleep for 2 seconds 35 time.Sleep(2 * time.Second) 36 // Close the file, releasing the guard 37 f.Close() 38 39 fmt.Println("Guard released") 40 }() 41 42 // Wait for the exit signal 43 <-exit 44 45 // Delete the file 46 f.Remove() 47 }