C++ – WaitForSingleObject( )

c++multithreadingwinapi

I have got myself stuck into a really amazing issue here.The code is like as below.

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;
 } 

Problem :

When the above code is run,sometimes( 1 out of 5 ) it hangs and the control gets stuck in the call to WaitforSingleObject()( inside the main function ).The code always calls SetEvent() function to ensure that the thread would terminate before calling Wait() function.

I do not see any reason why it should ever hang?

Best Solution

The problem is your use of the _beginthread API. You cannot use the handle returned from this function with the Win32 wait functions. You should use _beginthreadex or CreateThread. From 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.

Related Question