我阅读了一些关于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