August 2016
Beginner to intermediate
665 pages
14h 11m
English
Files are a great example of areas where data consistency issues such as race conditions can lead to more permanent and catastrophic problems. Let's look at a piece of code that might continuously attempt to update a file to see where we could run into race conditions, which in turn could lead to bigger problems such as an application failing or losing data consistency:
package main
import(
"fmt"
"io/ioutil"
"strconv"
"sync"
)
func writeFile(i int) {
rwLock.RLock();
ioutil.WriteFile("test.txt",
[]byte(strconv.FormatInt(int64(i),10)), 0x777)
rwLock.RUnlock();
writer<-true
}
var writer chan bool
var rwLock sync.RWMutex
func main() {
writer = make(chan bool)
for i:=0;i<10;i++ {
go writeFile(i)
}
<-writer
fmt.Println("Done!")
}Read now
Unlock full access