英文:
Resolving duplicate mutex lock in Go
问题
我在一个Go程序中有一堆函数,这些函数在一个使用互斥锁来管理对其函数的并发访问的结构体上工作。
其中一些函数在特定数据上操作,需要锁定,并且使用mutex.Lock()来获取管理对该数据访问的互斥锁。今天我遇到了一个问题,当两个这样的锁定方法互相调用时。当mutex.Lock()第二次被调用时,它会被阻塞 - 当然会这样。
我面临的问题与这段代码非常相似:http://play.golang.org/p/rPARZsordI
在Go中有没有解决这个问题的最佳实践?据我所知,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.
答案1
得分: 1
似乎是你系统的设计缺陷。你应该将需要同时加锁和解锁的部分分离出来。例如,如果你的代码是这样的:
func (t *Thing) A() { t.Lock(); defer t.Unlock(); t.foo(); t.B() }
func (t *Thing) B() { t.Lock(); defer t.Unlock(); t.bar() }
那么你应该改为:
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() }
英文:
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() }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论