Skip to content

Instantly share code, notes, and snippets.

@scukonick
Created June 24, 2017 22:48
Show Gist options
  • Save scukonick/7bfee57c71fafe8291a4e12c5eb0f570 to your computer and use it in GitHub Desktop.
Save scukonick/7bfee57c71fafe8291a4e12c5eb0f570 to your computer and use it in GitHub Desktop.
Golang Go Threadsafe write to the same file from multiple goroutines
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