簡體   English   中英

WaitForSingleObject不起作用

[英]WaitForSingleObject not work

請參見下面的代碼:

#include <windows.h>
int main(int argc, char* argv[])
{
    HANDLE _mutex = ::CreateMutex(NULL, FALSE, "abc");
    if (!_mutex)
        throw std::runtime_error("CreateMutex failed");

    if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
        throw std::runtime_error("WaitForSingleObject failed");

    printf("Must lock here\n");

    if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
        throw std::runtime_error("WaitForSingleObject failed");

    printf("Why come here????\n");
    return 0;
}

我不知道為什么控制台打印出來:

Must lock here
Why come here???

互斥體不起作用嗎? 我只希望結果顯示

Must lock here

並阻塞后打印上面的文字。

除了您的主線程外,沒有其他線程擁有互斥體的所有權。 這就是為什么它沒有阻塞並且您看到兩個打印語句的原因。 以下是MSDN鏈接的摘錄,其中清楚地說明了互斥鎖是如何工作的

線程獲得互斥量的所有權后,可以在重復調用wait函數時指定相同的互斥量,而不會阻止其執行。 這樣可以防止線程在等待已擁有的互斥鎖時自行死鎖。 要在這種情況下釋放其所有權,線程必須在互斥鎖每次滿足等待功能的條件時調用一次ReleaseMutex。

您可以創建多個線程來查看實際的阻止行為。 注意:您的代碼也缺少ReleaseMutex調用。

如果您想要一個行為像您描述的那樣的同步原語,則可以使用自動重置事件。

 #include <windows.h>
 #include <stdexcept>
 #include <stdio.h>
 int main(int argc, char* argv[])
 {
     HANDLE _mutex = ::CreateEvent(NULL, FALSE,         TRUE, NULL);
                                         // auto reset  // initially signalled
     if (!_mutex)
         throw std::runtime_error("CreateEvent failed");

     if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0) 
         throw std::runtime_error("WaitForSingleObject failed");
     // unsignalled now

     printf("Must lock here\n");

     // will block forever until someone calls SetEvent
     if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
         throw std::runtime_error("WaitForSingleObject failed");

     printf("Why come here????\n");
     return 0;
 }

更新:在C ++中閱讀互斥鎖

我不是c ++專家,但是線程擁有互斥鎖。 在您的示例中,同一線程打開/創建命名的互斥鎖,因此第二個調用將不會阻塞。

看一看:“使用互斥對象”。

http://msdn.microsoft.com/en-us/library/ms686927(v=VS.85).aspx

-Oisin

它不是“有效”的“原因”是沒有理由這樣做。 FALSE參數表明,您正在尋找現有的互斥對象。 閱讀文檔。 http://msdn.microsoft.com/en-us/library/ms682411%28VS.85%29.aspx

您確定要互斥而不是CRITICAL_SECTION嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM