我閱讀了一些關於Mutex的文檔,但仍然唯一的想法是它有助於防止線程訪問已被另一個資源使用的資源。有人可以解釋互斥體以及它如何使用?
我從代碼片段,並得到了執行工作正常:
#include <windows.h>
#include <process.h>
#include <iostream>
using namespace std;
BOOL FunctionToWriteToDatabase(HANDLE hMutex)
{
DWORD dwWaitResult;
// Request ownership of mutex.
dwWaitResult = WaitForSingleObject(
hMutex, // handle to mutex
5000L); // five-second time-out interval
switch (dwWaitResult)
{
// The thread got mutex ownership.
case WAIT_OBJECT_0:
__try
{
// Write to the database.
}
__finally {
// Release ownership of the mutex object.
if (! ReleaseMutex(hMutex)) {
// Deal with error.
}
break;
}
// Cannot get mutex ownership due to time-out.
case WAIT_TIMEOUT:
return FALSE;
// Got ownership of the abandoned mutex object.
case WAIT_ABANDONED:
return FALSE;
}
return TRUE;
}
void main()
{
HANDLE hMutex;
hMutex=CreateMutex(NULL,FALSE,"MutexExample");
if (hMutex == NULL)
{
printf("CreateMutex error: %d\n", GetLastError());
}
else if (GetLastError() == ERROR_ALREADY_EXISTS)
printf("CreateMutex opened existing mutex\n");
else
printf("CreateMutex created new mutex\n");
}
但哪一個線程,這裏是共享資源是什麼我不明白的是什麼?任何人都可以請解釋或提供更好的文章或文件?
您的程式碼片段似乎不完整,例如我看不到FunctionToWriteToDatabase被調用的地方。你能提供更多,你從哪裏得到它?如果你澄清了你的問題是關於一般的互斥鎖還是這個特定的代碼片斷,這也會很有幫助。 – danio 2010-08-20 07:26:16