gpt4 book ai didi

c++ - 嵌套临界区是否有效?

转载 作者:IT老高 更新时间:2023-10-28 22:08:16 27 4
gpt4 key购买 nike

例如,这是否有效?

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 );

显然,我绝不会故意这样做,但如果这是由于函数调用导致调用“第一级”以锁定对象以用于复杂(例如搜索)算法和“第二级”在该对象的访问器函数中被调用?

最佳答案

是的,进入相同的临界区是有效的。来自 the docs :

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.

关于c++ - 嵌套临界区是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7260432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com