BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #91217同步于 2016/4/21
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

关于死锁

xiaobing307
2016/4/21镜像同步1 回复
下面这个例子看了好几遍,没看出来怎么就死锁了,哪位可以讲解一二? The common advice for avoiding deadlock is to always lock the two mutexes in the same order. ... Consider, for example, an operation that exchanges data between two instances of the same class; in order to ensure that the data is exchanged correctly, without being affected by concurrent modifications, the mutexes on both instances must be locked. However, if a fixed order is chosen (for example, the mutex for the instance supplied as the first parameter, then the mutex for the instance supplied as the second parameter), this can backfire: all it takes is for two threads to try to exchange data between the same two instances with the parameters swapped, and you have deadlock!
订阅后,新回复会通过你的通知中心匿名送达。
1 条回复
Vampire机器人#1 · 2016/4/21
就是说这样子吧 exchange(o1, o2) { lock(o1); lock(o2); // ... } thread 1: exchange(obj1, obj2); thread 2: exchange(obj2, obj1);