[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
The concept of nested locks is derived from a programming scenario. What is the situation? Let's explain it in detail. Assume that you add a lock when processing a public function because the public data is involved in the middle. However, it is a bit sad. This public function also adds a lock and is the same as the lock you apply. Therefore, unless you are using a semaphore, your program will never be able to get this lock.
HANDLE hLock;void sub_func(){ /*...*/ WaitForSingleObject(hLock, INFINITE); do_something(); ReleaseMutex(hLock); /*...*/}void data_process(){ /*...*/ WaitForSingleObject(hLock, INFINITE); sub_func(); ReleaseMutex(hLock); /*...*/}
There are many reasons for this situation. One important aspect is that different people are responsible for each module of the software. In essence, we cannot determine what locks are used by others. You do not have the right to prevent others from using a lock. Therefore, in this case, you have to rely on yourself. Nested locks are a good solution.
(1) Data Structure of nested locks
typedef struct _NestLock{ int threadId; int count; HANDLE hLock;}NestLock;NestLock* create_nest_lock(HANLDE hLock){ NestLock* hNestLock = (NestLock*)malloc(sizeof(NestLock)); assert(NULL != hNestLock); hNestLock->threadId = hNestLock->count = 0; hNestLock->hLock = hLock; return hNestLock;}
(2) apply for nested locks
void get_nest_lock(NestLock* hNestLock){ assert(NULL != hNestLock); if(hNestLock->threadId == GetThreadId()) { hNestLock->count ++; }else{ WaitForSingleObject(hNestLock->hLock); hNestLock->count = 1; hNestLock->threadId = GetThreadId(); }}
(3) release the lock
void release_nest_lock(NestLock* hNestLock){ assert(NULL != hNestLock); assert(GetThreadId() == hNestLock->threadId); hNestLock->count --; if(0 == hNestLock->count){ hNestLock->threadId = 0; ReleaseMutex(hNestLock->hLock); }}
Summary:
(1) nested locks are not so much a new lock type as statistical locks.
(2) nested locks are the same as common locks and are very convenient to use.
(3) nested locks also have disadvantages, which cause trouble for Lock detection.