解决Go语言中的重复互斥锁问题

huangapple go评论89阅读模式
英文:

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() }

huangapple
  • 本文由 发表于 2015年10月23日 00:21:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/33285808.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定