[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.
-
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. 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
-
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 lock
-
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);
-
}
-
}
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