Daniel Eder
Daniel Eder

Reputation: 90

Resolving duplicate mutex lock in Go

I have a bunch of functions in a Go program that work on a struct that uses a mutex to manage concurrent access to its functions.

Some of these functions, that operate on specific data, need locks and thereby use mutex.Lock() to get hold of a mutex that manages the access to that data. Today I encountered an issue when two of these locking methods call each other. As soon as mutex.Lock() is called a second time it blocks - of course.

The problem I am facing is very similar to this code: http://play.golang.org/p/rPARZsordI

Is there any best-practise in Go on how to solve this issue? As far as I know recursive locks are not available in Go.

Upvotes: 0

Views: 538

Answers (1)

Ainar-G
Ainar-G

Reputation: 36189

It seems like a design flaw of your system. You should factor out the part that you need both locked and unlocked. E.g. if what you do is

func (t *Thing) A() { t.Lock(); defer t.Unlock(); t.foo(); t.B() }
func (t *Thing) B() { t.Lock(); defer t.Unlock(); t.bar() }

then what you should do instead is

func (t *Thing) A() { t.Lock(); defer t.Unlock(); t.foo(); t.b() }
func (t *Thing) B() { t.Lock(); defer t.Unlock(); t.b() }
func (t *Thing) b() { t.bar() }

Upvotes: 1

Related Questions