Skip to content

Instantly share code, notes, and snippets.

@dragonfax
Created September 10, 2015 23:11
Show Gist options
  • Save dragonfax/4a0da83b3bff3de791b6 to your computer and use it in GitHub Desktop.
Save dragonfax/4a0da83b3bff3de791b6 to your computer and use it in GitHub Desktop.
test reading concurrently from the same io.Reader
  1. dd if=/dev/urandom of=test.file bs=1m count=100
  2. go build
  3. ./ test.file

This will have several goroutines try to read the file from the same file descriptor. And show that they all get only a random subset of the file.

ZiggyPiggy:concurrent_reader jstillwell$ ls -l test.file
-rw-r--r-- 1 jstillwell staff 104857600 Sep 10 15:57 test.file
ZiggyPiggy:concurrent_reader jstillwell$ go build && ./concurrent_reader test.file
read 20973056 bytes
read 16776704 bytes
read 33553920 bytes
read 33553920 bytes
package main
import (
"fmt"
"io/ioutil"
"os"
"sync"
)
func main() {
filename := os.Args[1]
file, err := os.Open(filename)
if err != nil {
panic(fmt.Sprintf("failure to open filename given on command line '%s'", filename))
}
var wg sync.WaitGroup
f := func() {
defer wg.Done()
buf, err := ioutil.ReadAll(file)
if err != nil {
panic(err)
}
fmt.Printf("read %d bytes\n", len(buf))
}
for i := 0; i <= 3; i++ {
wg.Add(1)
go f()
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment