0

I'm doing c# course and found this example of lock:

public class MessageQueue<T>
{
    private readonly object _sync = new object();
    private readonly Queue<T> _queue = new Queue<T>();
    public void Post(T message)
    {
        lock (_sync)
        {
            bool wasEmpty = _queue.Count == 0;
            _queue.Enqueue(message);
            if (wasEmpty)
            {
                Monitor.Pulse(_sync);
            }
        }
    }
    public T Get()
    {
        lock (_sync)
        {
            while (_queue.Count == 0)
            {
                 Monitor.Wait(_sync);
            }
            return _queue.Dequeue();
        }
    }
}

is the right example? if anything will try to get items it will wait, but other thread won't be allow to post an message and use Pulse() function if item is locked??

Marcin
  • 1
  • 2
  • 3
    Just check the MSDN docs for Monitor.Wait(). Quote: "**Releases the lock** on an object and blocks the current thread until it reacquires the lock". So other threads are not blocked from entering Post() and calling Pulse(). It is the Pulse() call that allows Get() to reacquire the lock. Programmers are not expected to understand monitors, they use ConcurrentQueue instead. – Hans Passant Jun 06 '16 at 11:32
  • I'm not sure the `Pulse` should be in an `if`. It doesn't hurt to do a `Pulse` if the queue wasn't empty and I think certain race conditions could result in `Get` threads starving. – juharr Jun 06 '16 at 11:58

0 Answers0