Monitor vs WaitHandle based thread sync

前端 未结 3 1947
日久生厌
日久生厌 2020-12-08 02:54

I was under the impression, after reading this article that it is better to use Monitor/Lock for thread synchronisation as it does not use native resources

Specific q

3条回答
  •  孤城傲影
    2020-12-08 02:58

    I think I have a pretty good example of the 3rd bullet (and while this thread is a bit old, it might help someone).

    I've some code where thread A receives network messages, enqueues them, then pulses thread B. Thread B locks, dequeues any messages, unlocks the queue, then processes the messages.

    The problem arrives in that while Thread B is processing, and is not waiting, if A gets a new network message, enqueues and pulses... well, B isn't waiting so the pulse just evaporates. If B then finishes what it was doing and hits the Monitor.Wait(), then the recently added message will just hang around until another message arrives and the pulse is received.

    Note that this problem didn't really surface for a while, as originally my entire loop was something like:

    while (keepgoing)
      { 
      lock (messageQueue)
          {
          while (messageQueue.Count > 0)
              ProcessMessages(messageQueue.DeQueue());
    
          Monitor.Wait(messageQueue);
          }
      }
    

    This problem didn't crop up (well, there were rare oddities on shutdown, so I was a bit suspicious of this code) until I decided that the (potentially long running) message processing shouldn't keep the queue locked as it had no reason to. So I changed it to dequeue the messages, leave the lock, THEN do the processing. And then it seemed like I started missing messages, or they would only arrive after a second event happened...

提交回复
热议问题