多层SRWLock是否有效?

时间:2015-06-08 11:07:17

标签: c++ winapi

例如,此代码有效吗?

SRWLOCK srwLockA;
SRWLOCK srwLockB;

::InitializeSRWLock( &srwLockA);
::InitializeSRWLock( &srwLockB);

::AcquireSRWLockExclusive( &srwLockA );      // First level

/* do some stuff with member A*/

::AcquireSRWLockExclusive( &srwLockB );      // Second level

/* do some stuff with member A & B */

::ReleaseSRWLockExclusive( &srwLockB );        // Second level

/* do some stuff with member A**/

::ReleaseSRWLockExclusive( &srwLockA );      // First level

srwLockA和srwLockB分别用于保护成员A和B. 我只是想知道SRWlock可以这样使用。

2 个答案:

答案 0 :(得分:0)

这应该有用。

“递归获取锁定”意味着两次获取相同的锁。例如:

SRWLOCK lock;
::InitializeSRWLock( &lock );

::AcquireSRWLockExclusive( &lock ); // acquire the lock
// Now we have the lock
::AcquireSRWLockExclusive( &lock ); // acquire the lock again!?
// Now we still have the lock

::ReleaseSRWLockExclusive( &lock ); // release the lock
// Now we STILL have the lock?
::ReleaseSRWLockExclusive( &lock ); // release the lock again
// Now we don't.

这不适用于SRW锁。它适用于某些类型的锁,例如互斥锁(当然,对于互斥锁,您可以使用WaitForSingleObjectReleaseMutex而不是AcquireSRWLockExclusiveReleaseSRWLockExclusive

你可以获得多个不相关的锁,因为他们对彼此一无所知。

答案 1 :(得分:0)

FWIW,我对它的解读(在测试之前不是100%保证是正确的):

  • 可以在同一个线程中获取SRWLock,同时已经获取了同一线程中的另一个SRWLock

  • 在同一个线程中已经获取相同的 SRWLock时,无法在同一个线程中重新获取SRWLock;最有可能的是,这种递归获取相同锁的尝试将导致无限的自死(类似于* nix中的非递归互斥锁)。