2 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個(gè)贊
當(dāng)另一個(gè)線程一直占著mutex的時(shí)候才會(huì)等待
#include <windows.h>
#include <process.h>
HANDLE mutex = NULL;
unsigned int _stdcall threadfun( void* o )
{
while( true )
{
WaitForSingleObject(mutex,INFINITE);
printf( "press key\n" );
getchar(); //當(dāng)這里一直占著的時(shí)候,主線程就一直等,直到這里releasemutex
ReleaseMutex( mutex );
}
return 0;
}
int main( int argc, char** argv )
{
mutex = CreateMutex(NULL,false,NULL);
_beginthreadex( NULL, 0, threadfun, 0, 0, 0 );
while(true)
{
WaitForSingleObject(mutex, INFINITE);
printf( "me\n" );
ReleaseMutex(mutex);
}
return 0;
}

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
當(dāng)singleMutex被觸發(fā)后才會(huì)繼續(xù)執(zhí)行,否則會(huì)一直等待。
WaitForSingleObject是windows的一個(gè)API:
1 函數(shù)聲明:
DWORD WaitForSingleObject(
HANDLE hHandle,
DWORD dwMilliseconds
);
2 函數(shù)說明:
hHandle[in]對(duì)象句柄??梢灾付ㄒ幌盗械膶?duì)象,如Event、Job、Memory resource notification、Mutex、Process、Semaphore、Thread、Waitable timer等。
dwMilliseconds[in]定時(shí)時(shí)間間隔,單位為milliseconds(毫秒).如果指定一個(gè)非零值,函數(shù)處于等待狀態(tài)直到hHandle標(biāo)記的對(duì)象被觸發(fā),或者時(shí)間到了。如果dwMilliseconds為0,對(duì)象沒有被觸發(fā)信號(hào),函數(shù)不會(huì)進(jìn)入一個(gè)等待狀態(tài),它總是立即返回。如果dwMilliseconds為INFINITE,對(duì)象被觸發(fā)信號(hào)后,函數(shù)才會(huì)返回。
添加回答
舉報(bào)