duan19780629 2015-10-22 16:21
浏览 243
已采纳

解决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条回答 默认 最新

  • 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() }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱