Multithreading 如何在不输入的情况下测试临界段是否已锁定?或者,如何等待一个critsec被另一个线程拥有?
出于开发目的,我正在努力强制一致地重现某些死锁场景。这样做有助于让一个线程等待一个关键部分被另一个线程锁定,然后强制它阻塞 所以,我想要这样的东西:Multithreading 如何在不输入的情况下测试临界段是否已锁定?或者,如何等待一个critsec被另一个线程拥有?,multithreading,winapi,deadlock,Multithreading,Winapi,Deadlock,出于开发目的,我正在努力强制一致地重现某些死锁场景。这样做有助于让一个线程等待一个关键部分被另一个线程锁定,然后强制它阻塞 所以,我想要这样的东西: void TryToWaitForBlock(CriticalSection& cs, DWORD ms) { // wait until this CS is blocked, then return } ... void someFunction() { // ... TryToWaitForBlock(cs
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.
// ...
}
tryIntercriticalSection
将是完美的,但由于它实际上将进入临界区,因此不可用。是否有类似的功能可以执行测试,但不尝试输入它?bool TryToWaitForBlock(CRITICAL\u SECTION&cs,DWORD ms)
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;
}
{
大整数频率;
QueryPerformanceFrequency(&freq);
现在是大整数;
QueryPerformanceCounter(&now);
大整数等待;
waitill.QuadPart=静态_cast(now.QuadPart+freq.QuadPart*(ms/1000.0));
while(now.QuadPart
如果tryenterriticalsection
成功进入,您能否立即释放它?hrm,我的直觉是,TryEnter…
在事件流中太过混乱。但是仔细想想,它应该没有任何效果,尤其是对于这个临时调试代码。如果critsec在我的两次调用之间可用,它还消除了竞争条件。现在我只需要一个调用,比如,EnterCritSecButTryToBlockFirst()
。谢谢你的第二次猜测:)事实上,比赛条件仍然存在。但在这种情况下,这并不是什么大问题。我的大脑被炸了:/n如果你可以更改其他线程的代码,那么你可以做类似于WaitForSingleObject(事件)的事情;EnterCriticalSection(cs)
中的someFunction()
和EnterCriticalSection(cs);设置事件(事件)
。在这种情况下,someFunction()
中的线程将根据需要阻塞。