所以我只是在學習C++互斥體,而且我正在關注MSDN上的大多數示例。爲什麼我會超時?我使用Sleep()將互斥量超時設置爲2000毫秒,「假」進程設置爲250毫秒。你可以看到它處理一些罰款,然後開始吹了....我知道如果我把互斥超時時間設置爲60000ms,它會很好,但爲什麼我只想要一個250ms的過程高?另外,它爲什麼從threadid#1跳到threadid#25?VC++ Mutex問題
謝謝! 埃裏克
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686927(v=vs.85).aspx
int createMutex(char* mutexName)
{
#define THREADCOUNT 25
HANDLE aThread[THREADCOUNT];
DWORD ThreadID;
int i;
int ID[THREADCOUNT];
// Create a mutex with no initial owner
ghMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
(LPCWSTR)mutexName); // unnamed mutex
if (ghMutex == NULL)
{
return 1;
}
// Create worker threads
for(i=0; i < THREADCOUNT; i++)
{
ID[i] = i +1;
aThread[i] = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE) WriteToDatabase,
&ID[i], // no thread function arguments
0, // default creation flags
&ThreadID); // receive thread identifier
if(aThread[i] == NULL)
{
return 1;
}
}
// Wait for all threads to terminate
WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);
// Close thread and mutex handles
for(i=0; i < THREADCOUNT; i++) CloseHandle(aThread[i]);
CloseHandle(ghMutex);
return 0;
}
DWORD WINAPI WriteToDatabase(int *ID){
int threadID = *ID;
char buffer[256];
int MUTEX_TIMEOUT = 2000;
int FAKE_PROCESS_TIME_DELAY = 250;
DWORD dwWaitResult;
// Request ownership of mutex.
dwWaitResult = WaitForSingleObject(
ghMutex, // handle to mutex
MUTEX_TIMEOUT); // time-out interval
sprintf(buffer, "NEW THREAD STARTED: #%d\n", threadID);
printf(buffer);
if(dwWaitResult == WAIT_OBJECT_0){
// The thread got ownership of the mutex
sprintf(buffer, "DB WRITE STATED: #%d\n", threadID);
printf(buffer);
Sleep(FAKE_PROCESS_TIME_DELAY); //simulate a long running process (db process?) which creates a WAIT_TIMEOUT
sprintf(buffer, "DB WRITE COMPLETED: #%d\n", threadID);
printf(buffer);
dwCount++;
ReleaseMutex(ghMutex);
return TRUE;
}else{
switch(dwWaitResult){
case WAIT_ABANDONED:
sprintf(buffer, "MUTEX ERROR [%s] #%d\n", "WAIT_ABANDONED", threadID);
break;
case WAIT_TIMEOUT:
sprintf(buffer, "MUTEX ERROR [%s] #%d\n", "WAIT_TIMEOUT", threadID);
break;
default:
sprintf(buffer, "MUTEX ERROR [%s] #%d\n", "UNKNOWN", threadID);
}
printf(buffer);
MutexERRORs++;
//ReleaseMutex(ghMutex);
return FALSE;
}
return TRUE;
}
銥星,我的印象是,超時是針對當前擁有互斥量的線程。你是說互斥隊列中的每個線程都有自己的超時計數器嗎? – kenyu73
@ kenyu73您指定的超時時間是線程*調用WaitForSingleObject函數等待獲取互斥量的最長時間。如果它在那段時間沒有獲得它,它會返回'WAIT_TIMEOUT'。它對那個線程持有*互斥量沒有任何影響。 – Iridium
這意味着如果數據不是時間敏感的,那麼WaitForSingleObject的大多數實現都希望使用INFINITE。 – kenyu73