c – WaitForSingleObject()
发布时间:2020-12-16 10:50:05 所属栏目:百科 来源:网络整理
导读:我在这里遇到了一个非常惊人的问题.代码如下所示. class A{ public: A(){ m_event = CreateEvent(NULL,false,NULL); // create an event with initial value as non-signalled m_thread = _beginthread(StaticThreadEntry,this); // create a thread } stati
我在这里遇到了一个非常惊人的问题.代码如下所示.
class A { public: A(){ m_event = CreateEvent(NULL,false,NULL); // create an event with initial value as non-signalled m_thread = _beginthread(StaticThreadEntry,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()的调用中(在main函数内).代码总是调用SetEvent()函数来确保线程终止在调用Wait()函数之前. 我没有看到为什么它应该挂起来的任何理由? 解决方法
问题是您使用_beginthread API.您不能使用Win32等待函数从此函数返回的句柄.您应该使用_beginthreadex或CreateThread.来自MSDN:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |