等待完全释放的信号量?

时间:2011-02-28 18:39:04

标签: .net multithreading concurrency semaphore

是否有可能(在.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);
        }



    }
}

1 个答案:

答案 0 :(得分:1)

此处需要两个同步对象。一个你已经得到的,一个信号量模型表。你需要另一个来模拟门。一个事件。

相关问题