Multithreaded things (nested locks)

[notice: All Rights Reserved. Please reprint. Do not use for commercial purposes. Contact email: feixiaoxing@163.com]

The concept of nested lock is mainly extended according to a situation in programming. What's the situation? We can explain it in detail. Suppose that when you are dealing with a public function, you add a lock because the public data is involved. But it's a little sad. The public function itself also adds a lock, which is the same as the lock you add. So unless you use semaphores, your program won't get the lock for life.

  1. HANDLE hLock;  
  2.   
  3. void sub_func()  
  4. {  
  5.     /*...*/  
  6.     WaitForSingleObject(hLock, INFINITE);  
  7.     do_something();  
  8.     ReleaseMutex(hLock);  
  9.     /*...*/  
  10. }  
  11.   
  12. void data_process()  
  13. {  
  14.     /*...*/      
  15.     WaitForSingleObject(hLock, INFINITE);  
  16.     sub_func();  
  17.     ReleaseMutex(hLock);  
  18.     /*...*/  
  19. }  
There are many reasons for this. One important aspect is that different people are responsible for each module of the software. So essentially, we can't be sure what kind of lock someone else is using. You have no right not to let someone else use a lock. So, in this case, it's up to you. Nested locks are a good solution.


(1) data structure of nested lock

  1. typedef struct _NestLock  
  2. {  
  3.     int threadId;  
  4.     int count;  
  5.     HANDLE hLock;  
  6. }NestLock;  
  7.   
  8. NestLock* create_nest_lock(HANLDE hLock)  
  9. {  
  10.     NestLock* hNestLock = (NestLock*)malloc(sizeof(NestLock));  
  11.     assert(NULL != hNestLock);  
  12.   
  13.     hNestLock->threadId = hNestLock->count = 0;  
  14.     hNestLock->hLock = hLock;  
  15.     return hNestLock;  
  16. }  

(2) apply for nested lock

  1. void get_nest_lock(NestLock* hNestLock)  
  2. {  
  3.     assert(NULL != hNestLock);  
  4.   
  5.     if(hNestLock->threadId == GetThreadId())  
  6.     {  
  7.         hNestLock->count ++;  
  8.     }else{  
  9.         WaitForSingleObject(hNestLock->hLock);  
  10.         hNestLock->count = 1;  
  11.         hNestLock->threadId = GetThreadId();  
  12.     }  
  13. }  

(3) release the lock

  1. void release_nest_lock(NestLock* hNestLock)  
  2. {  
  3.     assert(NULL != hNestLock);  
  4.     assert(GetThreadId() == hNestLock->threadId);  
  5.   
  6.     hNestLock->count --;  
  7.     if(0 == hNestLock->count){  
  8.         hNestLock->threadId = 0;  
  9.         ReleaseMutex(hNestLock->hLock);  
  10.     }  
  11. }  

Article summary:
(1) nested lock is not so much a new lock type as a statistical lock
(2) nested lock is as convenient as ordinary lock
(3) nested locks also have disadvantages, which brings troubles to our lock detection

Keywords: Programming

Added by feckless on Mon, 04 May 2020 12:07:34 +0300