C ++ multi-threaded - Deadlock

I believe there are too many friend-threaded programming experience, have eaten bitter deadlock. Unless you do not use multiple threads, or the possibility of a deadlock it will always exist. Why is there a deadlock it? I think the reason is mainly the following aspects:
(1) differences in personal experience using the lock
(2) module locks difference
differences between versions (3)
Difference (4) between the branches
(5) to modify the code and weight configuration brings difference codes

Whatever the reason, the deadlock of the crisis are there. So, what are typically present deadlock it? We can one by one over here,

Forget to release a lock
void data_process()  
{  
    EnterCriticalSection();  
  
    if(/* error happens */)  
        return;  
  
    LeaveCriticalSection();  
} 
Repeat single-threaded application lock
void sub_func()  
{  
    EnterCriticalSection();  
    do_something();  
    LeaveCriticalSection();  
}  
  
void data_process()  
{  
    EnterCriticalSection();  
    sub_func();  
    LeaveCriticalSection();  
}
Dual-threaded multi-lock application
void data_process1()  
{  
    EnterCriticalSection(&cs1);  
    EnterCriticalSection(&cs2);  
    do_something1();  
    LeaveCriticalSection(&cs2);  
    LeaveCriticalSection(&cs1);  
}  
  
void data_process2()  
{  
    EnterCriticalSection(&cs2);  
    EnterCriticalSection(&cs1);  
    do_something2();  
    LeaveCriticalSection(&cs1);  
    LeaveCriticalSection(&cs2);  
}  
Application lock ring
/* 
*             A   -  B 
*             |      | 
*             C   -  D 
*/  

Suppose A, B, C, D four people eat together around each have a chopstick. So, if there is which one wants to eat, he must first pick up the chopsticks on the left, and then pick up right chopstick. Now, while we let all the people began to eat. Then it is this situation that may arise. Everyone picked up the chopsticks on the left, or everyone picked up the chopsticks on the right to eat, they are now waiting for the other one chopstick. At this point everyone wants to eat, but everyone does not want to give up a bird've got their own chopsticks. So in fact we all eat rice.

Summary:
(1) there is always the risk of deadlock, but we should try to reduce the scope of this hazard exists
(2) the cost of solving the deadlock is extraordinarily high cost of
the best Deadlock method (3) is in programming when possible deadlock is detected
(4) multithreading is a double edged sword, with the increase of efficiency of course there is a risk of deadlock
(5) certain deadlock programs can be tolerated, big deal to restart the machine, However, some programs will not do

Released 1024 original articles · won praise 810 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_42528266/article/details/103902727