Monitor.Pulse()有条件

时间:2019-03-04 14:32:37

标签: c# multithreading

我有一个课,应该是线程安全的。由于所有方法都会更改对象状态变量,因此我最好希望使用单个同步对象来管理线程安全性,以避免复杂的问题。因此,我在该对象上包装了带有锁定语句的方法主体。 在某些情况下,需要释放锁一段时间,以允许另一个线程更新状态。到目前为止,只需使用Monitor.Wait()Monitor.Pulse()。 但是,我想对条件进行“脉冲化”。在下面的代码中,我只想向在'Send()'方法中等待的线程发送'Pulse'。同样,仅向在“ Receive()”方法中等待的线程发送“脉冲”。

总结一下:

  • 我更喜欢使用单个同步对象进行锁定,因为这四种方法均会更改对象状态变量。
  • Wait()应该释放锁定,但是要等待特定的脉冲。收到通知后,应重新获取该锁。
  • Pulse()应该仅通知一个等待线程,即发送或接收等待者。
  • 最好还可以使用CancellationToken来取消等待。

我尝试了很多事情,包括Monitor,Semaphore和WaitHandle组合,带有WaitHandles的队列以及更多创意选项。另外,我一直在玩多个同步对象。但是在每种情况下,我只能得到部分功能。

下面的代码是我得到的最接近的代码。 TODO注释显示代码有什么问题。

public class Socket
{
    public class Item { }

    private object sync = new object();
    private ManualResetEvent receiveAvailable = new ManualResetEvent(false);

    private Queue<Item> receiveQueue = new Queue<Item>();

    // used by client, from any thread
    public void Send(Item item, CancellationToken token)
    {
        lock (this.sync)
        {
            // sends the message somewhere and should await confirmation.
            // note that the confirmation order matters.

            // TODO: Should only continue on notification from 'NotifySent()', and respect the cancellation token
            Monitor.Wait(this.sync); 
        }
    }

    // used by client, from any thread
    public Item Receive(CancellationToken token)
    {
        lock (this.sync)
        {
            if (!this.receiveAvailable.WaitOne(0))
            {
                // TODO: Should only be notified by 'EnqueueReceived()' method, and respect the cancellation token.
                Monitor.Wait(this.sync);
            }

            var item = this.receiveQueue.Dequeue();
            if (this.receiveQueue.Count == 0)
            {
                this.receiveAvailable.Reset();
            }

            return item;
        }
    }

    // used by internal worker thread
    internal void NotifySent()
    {
        lock (this.sync)
        {
            // Should only notify the Send() method.
            Monitor.Pulse(this.sync);
        }
    }

    // used by internal worker thread
    internal void EnqueueReceived(Item item)
    {
        lock (this.sync)
        {
            this.receiveQueue.Enqueue(item);
            this.receiveAvailable.Set();

            // TODO: Should only notify the 'Receive()' method.
            Monitor.Pulse(this.sync);
        }
    }
}

旁注: 在python中,可以使用threading.Condition(忽略CancellationToken)来实现我的要求。也许C#中提供了类似的构造?

class Socket(object):
    def __init__(self):
        self.sync = threading.RLock()
        self.receive_queue = collections.deque()
        self.send_ready = threading.Condition(self.sync)
        self.receive_ready = threading.Condition(self.sync)

    def send(self, item):
        with self.send_ready:
            // send the message
            self.send_ready.wait()

    def receive(self):
        with self.receive_ready:
            try:
                return self.receive_queue.popleft()
            except IndexError:
                self.receive_ready.wait()
            return self.receive_queue.popleft()

    def notify_sent(self):
        with self.sync:
            self.send_ready.notify()

    def enqueue_received(self, item):
        with self.sync:
            self.receive_queue.append(item)
            self.receive_ready.notify()

2 个答案:

答案 0 :(得分:1)

您要查找的是条件变量,该变量不会直接在任何.NET API中公开。 Monitor是最接近您要查找的内置类型,它是Mutex与单个条件变量结合使用。

.NET中解决此问题的标准方法是在继续操作之前始终重新检查条件(在等待侧)。这对于处理虚假唤醒(can happen for all Condition Variable-based solutions)也是必需的。

因此:

// Note: 'while', not 'if'
while (!this.receiveAvailable.WaitOne(0))
{
  Monitor.Wait(this.sync);
}

等等。

在.NET中,由于没有条件变量,因此与指定条件相比,您会有更多的虚假唤醒,但是即使在指定条件的情况下,也会发生虚假唤醒。 / p>

答案 1 :(得分:0)

由于您的评论,我相信我已经找到了解决问题的方法。我决定将状态变量分为一个外部类,因此锁定套接字和在客户端管理线程安全变得更加容易。这样,我可以在一个线程中自己管理状态变量(在单独的类中,在下面的代码中未显示)。

这是我想出的综合解决方案:

public class Socket
{
    public class Item { }

    private class PendingSend
    {
        public ManualResetEventSlim ManualResetEvent { get; set; }
        public bool Success { get; set; }
        public string Message { get; set; }
        public Exception InnerException { get; set; }
    }

    private readonly object sendLock = new object();
    private readonly object receiveLock = new object();
    private readonly ManualResetEventSlim receiveAvailable
        = new ManualResetEventSlim(false);
    private readonly SemaphoreSlim receiveSemaphore 
        = new SemaphoreSlim(1, 1);

    private readonly ConcurrentQueue<Item> sendQueue
        = new ConcurrentQueue<Item>();
    private readonly ConcurrentQueue<PendingSend> pendingSendQueue
        = new ConcurrentQueue<PendingSend>();
    private readonly ConcurrentQueue<Item> receiveQueue
        = new ConcurrentQueue<Item>();

    // Called from any client thread.
    public void Send(Item item, CancellationToken token)
    {
        // initialize handle to wait for.
        using (var handle = new ManualResetEventSlim(false))
        {
            var pendingSend = new PendingSend
            {
                ManualResetEvent = handle
            };

            // Make sure the item and pendingSend are put in the same order.
            lock (this.sendLock)
            {
                this.sendQueue.Enqueue(item);
                this.pendingSendQueue.Enqueue(pendingSend);
            }

            // Wait for the just created send handle to notify.
            // May throw operation cancelled, in which case the message is
            // still enqueued... Maybe fix that later.
            handle.Wait(token);

            if (!pendingSend.Success)
            {
                // Now we actually have information why the send 
                // failed. Pretty cool.
                throw new CommunicationException(
                    pendingSend.Message, 
                    pendingSend.InnerException);
            }
        }
    }

    // Called by internal worker thread.
    internal Item DequeueForSend()
    {
        this.sendQueue.TryDequeue(out Item result);

        // May return null, that's fine
        return result;
    }

    // Called by internal worker thread, in the same order items are dequeued.
    internal void SendNotification(
        bool success,
        string message,
        Exception inner)
    {
        if (!this.pendingSendQueue.TryDequeue(out PendingSend result))
        {
            // TODO: Notify a horrible bug has occurred.
        }

        result.Success = success;
        result.Message = message;
        result.InnerException = inner;

        // Releases that waithandle in the Send() method.
        // The 'PendingSend' instance now contains information about the send.
        result.ManualResetEvent.Set();
    }

    // Called by any client thread.
    public Item Receive(CancellationToken token)
    {
        // This makes sure clients fall through one by one.
        this.receiveSemaphore.Wait(token);

        try
        {
            // This makes sure a message is available.
            this.receiveAvailable.Wait(token);

            if (!this.receiveQueue.TryDequeue(out Item result))
            {
                // TODO: Log a horrible bug has occurred.
            }

            // Make sure the count check and the reset happen in a single go.
            lock (this.receiveLock)
            {
                if (this.receiveQueue.Count == 0)
                {
                    this.receiveAvailable.Reset();
                }
            }

            return result;
        }
        finally
        {
            // make space for the next receive
            this.receiveSemaphore.Release();
        }
    }

    // Called by internal worker thread.
    internal void EnqueueReceived(Item item)
    {
        this.receiveQueue.Enqueue(item);

        // Make sure the set and reset don't intertwine
        lock (this.receiveLock)
        {
            this.receiveAvailable.Set();
        }
    }
}