【发布时间】:2011-04-01 12:41:21
【问题描述】:
我阅读了一些关于 Mutex 的文档,但我得到的唯一想法是它有助于防止线程访问已被另一个资源使用的资源。
我从 Code sn-p 得到并执行,效果很好:
#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");
}
但我不明白的是线程在哪里,共享资源在哪里?谁能解释或提供更好的文章或文件?
【问题讨论】:
-
您的代码 sn-p 似乎不完整,例如我看不到 FunctionToWriteToDatabase 的调用位置。你能提供更多吗?你从哪里得到的?如果您澄清您的问题是关于一般互斥锁还是此特定代码 sn-p,这也会有所帮助。
标签: c++ windows multithreading mutex