2015-10-22 16:21
浏览 185


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.

图片转代码服务由CSDN问答提供 功能建议

我在Go程序中有很多函数,这些函数在使用互斥体管理对并发访问的结构上起作用 它的功能。

其中一些对特定数据进行操作的功能需要锁,从而使用mutex.Lock()来获取用于管理对数据访问权限的互斥量。 今天,当其中两个锁定方法相互调用时,我遇到了一个问题。 当然,一旦再次调用Mutex.Lock()就会阻止它。

我面临的问题与以下代码非常相似: http://play.golang.org/p/rPARZsordI

有什么最好的方法吗? 在Go上实践如何解决这个问题? 据我所知,Go中没有递归锁。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxie5930 2015-10-22 16:37

    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() }
    打赏 评论

相关推荐 更多相似问题