【问题标题】:Waiting for a fully released semaphore?等待完全释放的信号量?
【发布时间】:2023-03-14 02:29:01
【问题描述】:

是否有可能(在 .net 中)让线程等待信号量“完全发出信号”?具体来说,这就是我正在寻找的:

在主线程中创建信号量。 使用 .WaitOne() 将许多其他线程排队。 释放所有信号量的句柄。 等待其所有句柄为“空”。 在主线程中恢复操作。

为清楚起见,这里是一些经过精心设计的代码:

using System;
using System.Threading;

namespace ConcurrencySample01
{
    class Program
    {
        private static Semaphore _MaitreD = new Semaphore(0, 4);
        private static Random _Rnd = new Random();

        static void Main(string[] args)
        {
            Console.WriteLine("The restaurant is closed. No one can eat.");
            Thread.Sleep(1000);

            for (int i = 1; i <= 6; i++)
            {
                Thread t = new Thread(Diner);
                t.Start(i);
            }
            Console.WriteLine("The restaurant is opening.");
            Console.WriteLine("Empty seat count: {0}", 4 - _MaitreD.Release(4));

            // HERE IS WHERE I WANT TO WAIT.

            Console.WriteLine("The table is empty.");
            Console.ReadLine();

        }


        private static void Diner(object num)
        {
            Console.WriteLine("Diner {0} enters the restaurant and requests a seat.", num);
            _MaitreD.WaitOne();
            Console.WriteLine("Diner {0} sits down and begins to eat.", num);
            Thread.Sleep(1000 + _Rnd.Next(1000));
            Console.WriteLine("Diner {0} finishes and gets up.", num);
            Console.WriteLine("Empty seat count: {0}", _MaitreD.Release() + 1);
        }



    }
}

【问题讨论】:

    标签: .net multithreading concurrency semaphore


    【解决方案1】:

    这里需要两个同步对象。你已经得到了一个信号量模型表。你需要另一个来为门建模。一个事件。

    【讨论】:

    • 好收获。从概念上讲,“空”信号量可能并不意味着其使用寿命结束的原因有很多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    相关资源
    最近更新 更多