Working with files
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!") }
Get Go: Building Web Applications now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.