Threads and simple Dead lock cure

2019-02-16 19:34发布

When dealing with threads (specifically in C++) using mutex locks and semaphores is there a simple rule of thumb to avoid Dead Locks and have nice clean Synchronization?

9条回答
啃猪蹄的小仙女
2楼-- · 2019-02-16 19:53

If you want to attack the possibility of a deadlock you must attack one of the 4 crucial conditions for the existence of a deadlock.

The 4 conditions for a deadlock are: 1. Mutual Exclusion - only one thread can enter the critical section at a time. 2. Hold and Wait - a thread doesn't release the resources he acquired as long as he didn't finish his job even if other resources are un available. 3. No preemption - A thread doesn't have a priority over other threads. 4. Resource Cycle - There has to be a cycle chain of threads that waits for resources from other threads.

The easiest condition to attack is the resource cycle by making sure that no cycles are possible.

查看更多
放我归山
3楼-- · 2019-02-16 19:58

One way to ensure the ordering that other folks have talked about is to acquire locks in an order defined by their memory address. If at any point, you try to acquire a lock that should have been earlier in the sequence, you release all the locks and start over.

With a little work, it's possible to do this nearly automatically with some wrapper classes around the system primitives.

查看更多
迷人小祖宗
4楼-- · 2019-02-16 19:59

Read Deadlock: the Problem and a Solution.

"The common advice for avoiding deadlock is to always lock the two mutexes in the same order: if you always lock mutex A before mutex B, then you'll never deadlock. Sometimes this is straightforward, as the mutexes are serving different purposes, but other times it is not so simple, such as when the mutexes are each protecting a separate instance of the same class".

查看更多
登录 后发表回答