为什么在单独的线程中使用信号量会冻结程序?
Why does using a semaphore in a seperate thread freeze up the program?
我遇到了这个问题,所以我将其归结为仍然显示此错误的最小程序。我在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;
}
相关文章:
- 删除旧的信号量系统V
- 父进程和子进程之间的 POSIX 信号量
- 访问共享内存而不使用易失性、std::atomic、信号量、互斥锁和自旋锁
- 多线程.如果我使用信号量,我可以在开始时创建很多线程还是应该只有几个线程?
- C/C++ - 用于按顺序打印数字的 sem_t 类型的单个信号量
- 单车道桥 使用信号量进行同步
- 用于 64 位/32 位 IPC 的 POSIX 信号量的替代方案?
- 这个餐饮哲学家问题(dpp)的解决方案是如何工作的?互斥体和信号量
- 发布信号量返回错误 6(无效句柄)
- 在 C Linux 中使用三个线程使用信号量同步按顺序打印 3 4 5 50 次
- 在使用 pthread 和信号量实现生产者-消费者问题时需要帮助
- 如何让一个线程继续,而另一个线程正在等待C++中的信号量
- 实现信号量
- 计算信号量还是互斥体?
- POSIX 信号量在高争用/负载下不起作用
- C++:提升:托管共享内存是否需要信号量锁
- 信号量的问题
- 如何使用Windows API直接将进程"assign"到信号量?
- 从主线程C++更新信号量
- 为什么在单独的线程中使用信号量会冻结程序?