c++ - CreateMutex混淆

标签 c++ multithreading

所以我这样调用了createmutex

  while(1){
    HANDLE h;
    h=CreateMutex(NULL,TRUE,"mutex1");
    y=WaitForSingleObject(h,INFINITE);
    ///random code
    ReleaseMutex(h)
   }

它在循环两次后运行良好,但在第三次循环后在 WaitForSingleObject (h,INFINITE) 上死锁。这是两个线程同时运行。调用 ReleaseMutex 怎么会死锁呢? createmutex函数调用是否正确?

最佳答案

您正在等待一个已经拥有的互斥锁...请不要那样做。

此外,您并没有破坏互斥量,只是释放了它。下一次调用应该给你 ERROR_ALREADY_EXISTS。来自 MSDN 的完整报价是 "If the mutex is a named mutex and the object existed before this function call, the return value is a handle to the existing object, GetLastError returns ERROR_ALREADY_EXISTS, bInitialOwner is ignored, and the calling thread is not granted ownership."

如果任何“随机代码”等待另一个线程取得进展,它可能会在拥有互斥锁时死锁。在这种情况下,另一个线程将永远等待尝试获取互斥锁,这就是您所看到的行为。

关于c++ - CreateMutex混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5125342/

相关文章:

c++ - 数组引用速度与按位运算符

multithreading - java.lang.IllegalStateException : Not on FX application thread Calling Function

c# - 线程和 IEnumerable; "Collection Was Modified"- 异常

python - 在通过多线程进程运行时保持字典的完整性

c++ - 如何重载运算符 -= C++

c# - OpenGL闪烁问题

c++ - OpenCV C++ : error: 'it' does not name a type

c++ - Excel VBA 分配控制台 : Dll routine freezes after text selected in Console

ios - 使一个简单的 NSInteger 计数器线程安全

c# - .NET 4.0 和可怕的 OnUserPreferenceChanged 挂起