Created
June 24, 2017 22:48
-
-
Save scukonick/7bfee57c71fafe8291a4e12c5eb0f570 to your computer and use it in GitHub Desktop.
Golang Go Threadsafe write to the same file from multiple goroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package xxx | |
import ( | |
"fmt" | |
"io" | |
"os" | |
"strings" | |
"sync" | |
"testing" | |
) | |
func TestDiskWrite(t *testing.T) { | |
wg := sync.WaitGroup{} | |
for i := 0; i < 1000; i++ { | |
wg.Add(1) | |
go func(number int) { | |
f, err := os.OpenFile("/tmp/test.file.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) | |
if err != nil { | |
t.Fatal(err) | |
} | |
for j := 0; j < 1000; j++ { | |
r := strings.NewReader(fmt.Sprintf("goroutine: %d, loop: %d\n", number, j)) | |
_, err = io.Copy(f, r) | |
if err != nil { | |
t.Fatal(err) | |
} | |
} | |
err = f.Close() | |
if err != nil { | |
t.Fatal(f) | |
} | |
wg.Done() | |
}(i) | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment