是否有效嵌套关键部分? [英] Is it valid to nest a critical section?
问题描述
例如,这是否有效?
CRITICAL_SECTION cs;
::InitializeCriticalSection( &cs );
::EnterCriticalSection( &cs ); // First level
::EnterCriticalSection( &cs ); // Second level
/* do some stuff */
::LeaveCriticalSection( &cs ); // Second level
::LeaveCriticalSection( &cs ); // First level
::DeleteCriticalSection( &cs );
显然,我绝不会故意这样做,但如果这是因为函数调用,使得第一级被调用以锁定复杂(例如搜索)算法的对象,并且在该对象的访问器函数中调用第二级。
Obviously, I would never intentionally do this, but what if this were to come about as a result of function calls such that the "first level" gets called to lock an object for a complex (e.g. search) algorithm and the "second level" gets called in that object's accessor functions?
推荐答案
是的,它是有效的进入同一关键部分,而已经在它内部。从文档:
Yes it is valid to enter the same critical section while already inside it. From the docs:
在线程拥有临界区的所有权之后,它可以在不阻塞其执行的情况下对$ Enter $ Cr $ b额外调用EnterCriticalSection或TryEnterCriticalSection
。这防止线程从
死锁本身,同时等待它
已经拥有的关键部分。线程每次进入临界区
EnterCriticalSection和TryEnterCriticalSection成功。线程
每次进入
临界区时必须调用一次LeaveCriticalSection。
After a thread has ownership of a critical section, it can make additional calls to EnterCriticalSection or TryEnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns. The thread enters the critical section each time EnterCriticalSection and TryEnterCriticalSection succeed. A thread must call LeaveCriticalSection once for each time that it entered the critical section.
这篇关于是否有效嵌套关键部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!