我不明白多线程程序在执行以下操作时有什么区别:
WaitForSingleObject(hMutex, INFINITE);
// Critical secontion here
ReleaseMutex(hMutex);做一些更复杂的事情,比如在MSDN示例中
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; 
}发布于 2014-09-18 10:00:10
快速回答,但第一个示例假设WaitForSingleObject成功,而第二个示例处理(一些)错误。更重要的是,在第二个示例中,只有在互斥锁被安全获取的情况下,代码才会对受保护的数据进行操作,这意味着数据(理论上)处于已知状态。
WaitForSingleObject可能在这里返回两个可能的错误:WAIT_ABANDONED或WAIT_FAILED
WAIT_FAILED可能会发生,在这种情况下,您的软件可能会出错。在这种情况下,您可以记录它已经发生的事实,并尽可能干净地退出。WAIT_ABANDONED意味着持有互斥锁的线程已经退出或被杀死。不管怎样,您的程序处于未知状态,受保护的数据处于未知状态,您可能应该尽可能干净地退出.只是不要触摸数据,因为您不能安全地这样做。请记住,WAIT_ABANDONED可能是由某人在调试器中打开您的进程(或类似process )并杀死线程而产生的,而不仅仅是因为您自己的程序错误。所以你得处理好。我想这也会导致WAIT_FAILED .所以也要处理好。
https://stackoverflow.com/questions/25901610
复制相似问题