gpt4 book ai didi

multithreading - 如何在不输入的情况下测试临界区是否被锁定?或者,如何等到 critsec 被另一个线程拥有?

转载 作者:行者123 更新时间:2023-12-03 22:44:27 24 4
gpt4 key购买 nike

出于开发目的,我正在努力强制某些死锁场景持续重现。在这样做时,能够让一个线程等待一个关键部分被另一个线程锁定,然后强制它阻塞,这将很有帮助。

所以,我想要这样的东西:

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 是完美的,但是因为它实际上会进入临界区,所以不可用。是否有类似的功能可以进行测试,但不尝试输入它?

最佳答案

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

关于multithreading - 如何在不输入的情况下测试临界区是否被锁定?或者,如何等到 critsec 被另一个线程拥有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23570521/

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