c++ - 等待单个对象()

标签 c++ multithreading winapi

我在这里陷入了一个非常惊人的问题。代码如下。

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/

相关文章:

c++ - C++ 控制台应用程序中的 mp3 文件的 MCI_OPEN 失败

c++ - void* 到 FILE*... 这可能吗?

android - 利用 openGL 的多线程

Adobe After Effects 的 C# 互操作性

java - 为什么tomcat默认的线程池这么大?

java - 在 Android 中,如何让 Activity 在跳到下一个 Activity 之前等待?

java - 如何每秒移动 jlabel?

c# - 如何在另一个应用程序之上绘制图形/文本

winapi - 使用可变字符串调用 GetUserName WinAPI 函数不会填充字符串

C++:使用作为指向仅单实例类实例化的指针的全局变量是否不好?