Mutex gotchas

suggest change

Don’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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents