WaitForSingleObject ()

I myself am stuck in a really terrific problem. The code is as shown 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 runs, sometimes (1 out of 5) it freezes and the control gets stuck in the WaitforSingleObject () call (inside the main function). The code always calls the SetEvent () function to ensure that the thread stops before the Wait () function is called.

I see no reason why he should ever hang?

+3
source share
8 answers

The problem is using the _beginthread API. You cannot use the handle returned from this function with Win32 wait functions. You should use _beginthreadex or CreateThread. From MSDN:

; , , _beginthread ...

, _beginthreadex, API- , _beginthread.

+17

(, , ).

  • auto reset .
  • , .
  • .

, ( ), .

.

, , . , . DuplicateHandle WaitForSingleObject.

+2

SignalObjectAndWait SetEvent() WaitForSingleObject(), , , .

+1

, m_thread ?

, _beginthread - (, , , , ( , ), ).

_beginthreadex , , _endthreadex, , .

+1

, SetEvent WaitforSingleObject . WaitforSingleObject(m_event,INFINITE) .

0

, . , obj->ThreadEntry(), , , ThreadEntry, ThreadEntry , .

0

, SignalObjectAndWait .

MSDN :

, "" "" . , SignalObjectAndWait .

, , , , . , , -, , , . ?

0

: _beginthreadex, WFSO. , , , WFSO . ...

0

Source: https://habr.com/ru/post/1709979/


All Articles