go mutex example explain
tags: learning go programming
question
- in the example in go-mutex-basics,
mutexandcounterare two different and unrelated example, why doesmutex.Lock/Unlockaffectcounter?
content
- they ARE different and separate variables
mutexdoesn’t directly affectcounter- they have no intrinsic connection to each other
Note
- a mutex has no intrinsic connection with the things it’s protecting.
- it’s only a way of communication between threads.
- it’s basically a flag variable that a thread checks before doing something.
how does mutex actually work?
- a Mutex doesn’t lock variables
- a mutex has no knowledge of what’s the variable being protected
- a mutex itself is just a variable
- it’s a variable with two states, locked and unlocked
- when a go routine calls
mutex.Lock(), it simply:- either occupies the lock if the lock is free
- or blocks and waits until the lock is free
- it’s more like a way to “communicate” between go routines
- one go routine uses mutex to tell other go routines whether they can proceed or not
- it’s a synchronization mechanism between go routines