为什么在单独的线程中使用信号量会冻结程序?

Why does using a semaphore in a seperate thread freeze up the program?

本文关键字:信号量 冻结 程序 单独 线程 为什么      更新时间:2023-10-16

我遇到了这个问题,所以我将其归结为仍然显示此错误的最小程序。我在Windows上。

#include <windows.h>
#include <iostream>
HANDLE m_mutex;
void runFunction()
{
    ReleaseSemaphore(m_mutex, 1, NULL);
}
int main()
{
    std::cout << "Hello World!" << std::endl;
    m_mutex = CreateSemaphore(NULL, 1, 1, NULL);
    WaitForSingleObject(m_mutex, INFINITE);
    HANDLE m_handle = CreateThread(0, 5120, reinterpret_cast<LPTHREAD_START_ROUTINE>(runFunction), 0, 0, 0); 
    WaitForSingleObject(m_mutex, INFINITE);
    ReleaseSemaphore(m_mutex, 1, NULL);
    TerminateThread(m_handle, 0);
    CloseHandle(m_handle);
    CloseHandle(m_mutex);
    std::cout << "Done" << std::endl;
    return 0;
}

忽略糟糕的编码风格和TerminateThread的使用(我知道使用它是不好的),这是我正在测试的情况,而不是我将实现的情况。我仍然想知道为什么这会冻结程序,特别是当一些简单的事情,比如把std::cout << "Test" << std::endl;放在中间,使程序不再冻结。同时,"done"被打印出来,只是程序永远不会退出。

关于信号量的逻辑看起来没有问题。我的歉意。我没有注意到"1"。我只能提一下,你没有验证API函数实际上是否成功完成。

void runFunction()
{
    ReleaseSemaphore(m_mutex, 1, NULL);
}
int main()
{
    std::cout << "Hello World!" << std::endl;
    //OK - Count=1
    m_mutex = CreateSemaphore(NULL, 1, 1, NULL);
    WaitForSingleObject(m_mutex, INFINITE);
    //OK - Count=0
    HANDLE m_handle = CreateThread(0, 5120, reinterpret_cast<LPTHREAD_START_ROUTINE>(runFunction), 0, 0, 0); 
    //DO you know for sure that the thread has started??? The return value is never checked???
    //Now we not sure... Count may 1, or 0, because thread is not necessarily started immediately..
    //OK. We will block here. Count should no be 1 again, or should soon become it
    WaitForSingleObject(m_mutex, INFINITE);
    //Why???
    ReleaseSemaphore(m_mutex, 1, NULL);
    //Why so extreme? "Terminate thread is a dangerous function...." MSDN
    TerminateThread(m_handle, 0);
    CloseHandle(m_handle);
    CloseHandle(m_mutex);
    std::cout << "Done" << std::endl;
    return 0;
}