Skip to content

Instantly share code, notes, and snippets.

@donatello
Last active April 23, 2017 19:18
Show Gist options
  • Save donatello/08eec9a1847d0f9f2a73510460bae421 to your computer and use it in GitHub Desktop.
Save donatello/08eec9a1847d0f9f2a73510460bae421 to your computer and use it in GitHub Desktop.
Go Threads experiment - write system calls block
package main
import (
"fmt"
"os"
"sync"
)
var (
dir = "/tmp/writetest"
buf = []byte{}
)
func writeTask(id int) error {
f, err := os.Create(fmt.Sprintf("%s/%d", dir, id))
if err != nil {
return err
}
for times := 0; times < 10000; times++ {
_, err = f.WriteAt(buf, 0)
if err != nil {
return err
}
}
return f.Close()
}
func parallelWrite(n int) {
wg := sync.WaitGroup{}
wg.Add(n)
for i := 0; i < n; i++ {
go func(k int) {
err := writeTask(k)
if err != nil {
fmt.Printf("Thread %d: %v\n", k, err)
}
wg.Done()
}(i)
}
wg.Wait()
}
func main() {
buf = make([]byte, 1000000)
parallelWrite(1000)
}
@donatello
Copy link
Author

If you run the above program, and run ps huH p <PID_OF_PROCESS> | wc -l in a shell, you get the OS thread count of the process. The number of threads is always close to the argument of the parallelWrite() call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment