Skip to content

Instantly share code, notes, and snippets.

@chadlung
Last active June 2, 2016 07:21
Show Gist options
  • Save chadlung/de3aeefdabb230592abbf77cf6f5be8d to your computer and use it in GitHub Desktop.
Save chadlung/de3aeefdabb230592abbf77cf6f5be8d to your computer and use it in GitHub Desktop.
Fixing a race condition with a mutex (trivial example)
package main
import (
"fmt"
"sync"
)
func main() {
finished := make(chan bool, 1)
var i int
var mutex sync.Mutex
go func() {
mutex.Lock()
fmt.Println("In the Go routine reading to increment i")
i++
fmt.Println("New value of i:", i)
mutex.Unlock()
finished <- true
}()
mutex.Lock()
i++
mutex.Unlock()
<-finished
fmt.Println("Finished!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment