go mutex basics
tags: learning go programming
content
- Mutex: mutual exclusion
- make sure at any given time, there’s only one go routine that’s accessing a variable to avoid conflicts
- achieve by
LockandUnlockvariables
Note
mutex is a specific kind of locks
usage
- firstly, we need to create some variable that will be shared across different go routines, and a mutex to protect the shared resource:
var mutex sync.Mutex
counter := 0- then we need to lock and unlock the mutex
increment := func(value *int) {
mutex.Lock()
defer mutex.Unlock()
fmt.Println("im in go routine")
*value++
fmt.Println(*value)
}- if we trigger
incrementin parallel
for range 10 {
go increment(&counter)
}-
the result from
fmt.Printlnin go routines:- will always be from 1 to 10, in order
"im in go routine"is printed before counter
-
if there’s no
mutexlike shown below:- counter’s value printed out might not be in order
- all
"im in go routine"s are printed out all at once
increment := func(value *int) {
fmt.Println("im in go routine")
*value++
fmt.Println(*value)
}