As a beginner of golang, I find the mutex of golang is not re-entranceLock from the book The Go Programming Language
. And they explain the reason as:
There is a good reason Go’s mutexes are not re-entrant. The purpose of a mutex is to ensure that certain invariants of the shared variables are maintained at critical points during program execution. One of the invariants is "no goroutine is accessing the shared variables," but there may be additional invariants specific to the data structures that the mutex guards. When a goroutine acquires a mutex lock, it may assume that the invariants hold. While it holds the lock, it may update the shared variables so that the invariants are temporarily violated. However, when it releases the lock, it must guarantee that order has been restored and the invariants hold once again. Although a re-entrant mutex would ensure that no other goroutines are accessing the shared variables, it cannot protect the additional invariants of those variables.
it seemed the explain is detail enough, unfortunately I can't get it. I still don't know when we should use not re-entranceLock, and if not what bad surprise will I receive? I will appreciate if anyone can give me an example.
Here's an example of bad code just to illustrate the issue:
package main
import (
"fmt"
"sync"
)
type SafeCounter struct {
lock sync.Mutex
count int
enabled bool
NextValue func(int) int
}
const maxCount = 10
func (c *SafeCounter) Count() int {
return c.count
}
func (c *SafeCounter) Increment() {
c.lock.Lock()
if c.enabled {
c.count = c.NextValue(c.count)
}
c.lock.Unlock()
}
func (c *SafeCounter) SetEnabled(enabled bool) {
c.lock.Lock()
c.enabled = enabled
if !enabled {
c.count = 0
}
c.lock.Unlock()
}
func main() {
var counter SafeCounter
counter.SetEnabled(true)
counter.NextValue = func(value int) int {
if counter.Count() > maxCount {
// Safe counter doesn't expect this here!
// The program will panic in SetEnabled
counter.SetEnabled(false)
}
return value + 1
}
for i := 0; i < 100; i++ {
doAction()
counter.Increment()
}
fmt.Println(counter.Count())
}
func doAction() {
// some action
}
Both Increment
and SetEnabled
acquire locks because they can't allow the values of enabled
and count
to change while they're in the middle of something. However, if the lock was re-entrant (recursive), then it would be allowed (since both calls run on the same goroutine).