【发布时间】:2014-09-17 22:50:16
【问题描述】:
我不明白多线程程序中做的有什么区别:
WaitForSingleObject(hMutex, INFINITE);
// Critical secontion here
ReleaseMutex(hMutex);
做一些更复杂的事情,比如MSDN example:
dwWaitResult = WaitForSingleObject(
ghMutex, // handle to mutex
INFINITE); // no time-out interval
switch (dwWaitResult)
{
// The thread got ownership of the mutex
case WAIT_OBJECT_0:
__try {
// TODO: Write to the database
printf("Thread %d writing to database...\n",
GetCurrentThreadId());
dwCount++;
}
__finally {
// Release ownership of the mutex object
if (! ReleaseMutex(ghMutex))
{
// Handle error.
}
}
break;
// The thread got ownership of an abandoned mutex
// The database is in an indeterminate state
case WAIT_ABANDONED:
return FALSE;
}
【问题讨论】:
-
第一个例子假设
WaitForSingleObject成功,第二个例子考虑到它可能会失败。 -
@JonathanPotter 在将互斥体句柄传递给它时,WaitForSingleObject 何时会失败?
-
MSDN 没有比 FALSE 更大的武器,他们所能做的就是大写。 WAIT_ABANDONED 是适当的大写,它是您的代码中的一个讨厌的错误,您总是想知道。制造很多很多的噪音。不要犹豫 RaiseException。就像 dbase 提供者所做的那样。
-
@HansPassant 不确定我是否理解你的意思。
-
我必须努力解决更大的问题,David 的帖子是对此做一些事情的灵感。我什么时候找时间。
标签: c multithreading winapi mutex