我正在努力强制某些死锁场景一致地重现,以用于开发目的。在这样做时,能够让一个线程等到一个关键部分被另一个线程锁定,然后强制它阻塞它将会很有帮助。
所以,我想要这样的东西:
void TryToWaitForBlock(CriticalSection& cs, DWORD ms)
{
// wait until this CS is blocked, then return
}
...
void someFunction()
{
// ...
TryToWaitForBlock(cs, 5000);// this will give much more time for the crit sec to block by other threads, increasing the chance that the next call will block.
EnterCriticalSection(cs);// normally this /very/ rarely blocks. When it does, it deadlocks.
// ...
}
TryEnterCriticalSection
将完美,但因为它实际上会进入临界区,所以它不可用。是否有类似的功能可以进行测试,但也不会尝试输入它?
答案 0 :(得分:0)
bool TryToWaitForBlock( CRITICAL_SECTION& cs, DWORD ms )
{
LARGE_INTEGER freq;
QueryPerformanceFrequency( &freq );
LARGE_INTEGER now;
QueryPerformanceCounter( &now );
LARGE_INTEGER waitTill;
waitTill.QuadPart = static_cast<LONGLONG>(now.QuadPart + freq.QuadPart * (ms / 1000.0));
while( now.QuadPart < waitTill.QuadPart ) {
if( NULL != static_cast<volatile HANDLE&>(cs.OwningThread) ) {
return true;
}
QueryPerformanceCounter( &now );
}
return false;
}