我在这里陷入了一个非常惊人的问题。代码如下。
class A
{
public:
A(){
m_event = CreateEvent(NULL, false, false, NULL); // create an event with initial value as non-signalled
m_thread = _beginthread(StaticThreadEntry, 0, this); // create a thread
}
static void StaticThreadEntry(A * obj) { obj->ThreadEntry(); }
void ThreadEntry();
};
void A::ThreadEntry()
{
WaitforSingleObject(m_event,INFINITE);
}
int main()
{
A a;
SetEvent(m_event); // sets the event to signalled state which causes the running thread to terminate
WaitForSingleObject(m_thread, INFINITE); // waits for the thread to terminate
return 0;
}
问题:
当上面的代码运行时,有时(5 次中有 1 次)它挂起并且控件卡在对 WaitforSingleObject() 的调用中(在主函数内)。代码总是调用 SetEvent() 函数以确保线程将在调用 Wait() 函数之前终止。
我看不出它应该挂起的任何原因?
最佳答案
问题是您对 _beginthread API 的使用。您不能将此函数返回的句柄与 Win32 等待函数一起使用。您应该使用 _beginthreadex 或 CreateThread。来自 MSDN:
If successful, each of these functions returns a handle to the newly created thread; however, if the newly created thread exits too quickly, _beginthread might not return a valid handle...
You are ... able to use the thread handle returned by _beginthreadex with the synchronization APIs, which you cannot do with _beginthread.
关于c++ - 等待单个对象(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/964719/