Last active
June 2, 2016 07:21
-
-
Save chadlung/de3aeefdabb230592abbf77cf6f5be8d to your computer and use it in GitHub Desktop.
Fixing a race condition with a mutex (trivial example)
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 | |
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