WaitForSingleObject( )

Posted by Rakesh Agarwal on Stack Overflow See other posts from Stack Overflow or by Rakesh Agarwal
Published on 2009-06-08T12:39:08Z Indexed on 2010/04/15 18:33 UTC
Read the original article Hit count: 344

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about multithreading