MIKU_LINK_SUCCESS
MIKU_LINK_SUCCESS

Reputation: 43

Multi-thread dead lock:Will this design cause dead lock?

Thread A: set the variable m_bPaused and the m_pPauseEvent is a semaphore object which provides wait() and set() interface. Thread A call this to pause:

PausePlay(){
    m_bPaused = true;           // A1

    m_pPauseEvent->Wait(0);     //A2 wait for the B thread is enter to the waiting
}

Thread B:

    if (m_bPaused)
   {
       m_pPauseEvent->Set();    //B1
       m_pPauseEvent->Wait(0);  //B2 0 wait forever 
   }

And call Thread A to continue Thread B:

    m_bPaused = false;    //A3

    m_pPauseEvent->Set(); //A4 

When I pause, I wait until the B1 is executed.Thread A returns.Will here be dead lock? when I call the continue in Thread A,and run to A3. In the mean time thread B is still beteen B1 and and B2, then thead A finish the row m_pPauseEvent->Set(). Thread B will never received the signal sent by A4.Dead lock! Will this happen?

Upvotes: 0

Views: 128

Answers (3)

Anthony Williams
Anthony Williams

Reputation: 68561

Windows Events do not guarantee that a signal wakes one of the current waiters. This is the cause of the known issue with PulseEvent and missed wakeups, because the event is set and then cleared, but the set might not be seen by the waiting threads.

In this case, the Wait call following the Set call may wake rather than the Wait call on the other thread. This means that there is no synchronization protecting accesses to m_bPaused, which is UB, and also means that the wrong thread has woken.

Upvotes: 0

mkaes
mkaes

Reputation: 14119

Since you did not post the implementation of your event classes there might be multiple issues in your code.

  1. As already mentioned your access to m_bPaused might be an issue.
  2. Thread B calls Set() right before Wait(0). Are you sure that thread A will get notified or does Thread B consume the notification.
  3. In nearly all multi thread classes there is the problem of a spurious wake. It seems that your Thread B is not protected against this.

So it is really hard to tell if this code will be deadlock free or not.

Upvotes: 2

MSalters
MSalters

Reputation: 179779

Can't say for sure. m_bPaused is possibly a non-atomic variable which means the concurrent access is Undefined Behavior.

Upvotes: 1

Related Questions