Created
November 27, 2012 03:43
-
-
Save jimjh/4152221 to your computer and use it in GitHub Desktop.
Experiments with parallel read/write in Go without file.Sync or file.Close
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 main | |
// parallel_rw.go experiments with parallel read/write from a file without | |
// syncing (aka flushing) or closing. | |
import ( | |
"encoding/binary" | |
"fmt" | |
// "math/rand" | |
"os" | |
"runtime" | |
// "time" | |
) | |
var MAX uint32 = 1000 | |
func main() { | |
runtime.GOMAXPROCS(4) | |
file, err := os.Create("log") | |
if err != nil { | |
panic(err) | |
} | |
file.Close() | |
done := make(chan interface{}) | |
go read(done) | |
go write() | |
<-done | |
} | |
// read reads 0..MAX integers from the log file. | |
func read(done chan<- interface{}) { | |
file, err := os.OpenFile("log", os.O_RDONLY, 0666) | |
if nil != err { | |
panic(err) | |
} | |
var i uint32 | |
for i = 0; i < MAX; i = i { | |
var n uint32 | |
err := binary.Read(file, binary.LittleEndian, &n) | |
if nil != err { | |
fmt.Println("\t\t\t\t\t\tError: ", err.Error()) | |
continue | |
} | |
fmt.Println("Read ", n) | |
if i != n { | |
fmt.Printf("Corrupted data: expected %d, was %d\n", i, n) | |
os.Exit(1) | |
} | |
i++ | |
} | |
done <- nil | |
} | |
// write writes 0..MAX integers into the log file. | |
func write() { | |
file, err := os.OpenFile("log", os.O_WRONLY, 0666) | |
if nil != err { | |
panic(err) | |
} | |
var i uint32 | |
for i = 0; i < MAX; i++ { | |
if err := binary.Write(file, binary.LittleEndian, i); nil != err { | |
panic(err) | |
} | |
// time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) | |
fmt.Println("\t\t\tWrite ", i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With
MAX
set to10
, the output of a particular run looks like: