Mutex gotchas
suggest changeDon’t copy mutexes
A copy of sync.Mutex variable starts with the same state as original mutex but it is not the same mutex.
It’s almost always a mistake to copy a sync.Mutex e.g. by passing it to another function or embedding it in a struct and making a copy of that struct.
If you want to share a mutex variable, pass it as a pointer *sync.Mutex.
Mutex is not recursive (aka re-entrant)
In some languages mutexes are recursive i.e. the same thread can Lock the same mutex multiple times.
In Go sync.Mutex is non-recursive. Calling Lock twice in the same goroutine will deadlock.
go vet will warn you about copying mutexes. Here's an example warning:
> go vet
# github.com/ravendb/ravendb-go-client
.\document_conventions.go:151: assignment copies lock value to res: ravendb.DocumentConventions contains sync.Mutex
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents