有没有Semaphore的操作实例?

[已解决] 有没有Semaphore的操作实例?

5
[软件及编程 > C#]
有没有Semaphore的操作实例?
提问时间:2010/7/16 18:43:03 | 提问者:GaLiJiKuai | 悬赏:5 | 浏览:231
最佳答案
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication2
{

   public class Example
   {
       // A semaphore that simulates a limited resource pool.
       //
       private static Semaphore _pool;

       // A padding interval to make the output more orderly.
       private static int _padding;

       public static void Main()
       {
           // Create a semaphore that can satisfy up to three
           // concurrent requests. Use an initial count of zero,
           // so that the entire semaphore count is initially
           // owned by the main program thread.
           //
           _pool = new Semaphore(0, 3);

           // Create and start five numbered threads.
           //
           for (int i = 1; i <= 5; i++)
           {
               Thread t = new Thread(new ParameterizedThreadStart(Worker));

               // Start the thread, passing the number.
               //
               t.Start(i);
           }

           // Wait for half a second, to allow all the
           // threads to start and to block on the semaphore.
           //
           Thread.Sleep(500);

           // The main thread starts out holding the entire
           // semaphore count. Calling Release(3) brings the
           // semaphore count back to its maximum value, and
           // allows the waiting threads to enter the semaphore,
           // up to three at a time.
           //
           Console.WriteLine("Main thread calls Release(3).");
           _pool.Release(3);

           Console.WriteLine("Main thread exits.");
           Console.ReadLine();
       }

       private static void Worker(object num)
       {
           // Each worker thread begins by requesting the
           // semaphore.
           Console.WriteLine("Thread {0} begins " +
               "and waits for the semaphore.", num);
           _pool.WaitOne();

           // A padding interval to make the output more orderly.
           int padding = Interlocked.Add(ref _padding, 100);

           Console.WriteLine("Thread {0} enters the semaphore.", num);

           // The thread's "work" consists of sleeping for
           // about a second. Each thread "works" a little
           // longer, just to make the output more orderly.
           //
           Thread.Sleep(1000 + padding);

           Console.WriteLine("Thread {0} releases the semaphore.", num);
           Console.WriteLine("Thread {0} previous semaphore count: {1}",
               num, _pool.Release());
       }
   }

}
回答时间:2010/7/16 18:44:19 | 回答者:zsu
其他参考答案(0)
提交失败!请检查错误!错误信息:

注:以上所有信息由网友提供,仅供交流、参考,均不代表盛派网络言论,如果有任何问题或不妥,请立即联系我们

以下信息或许对您有用: