Semaphore,即信号量的意思。是操作系统原始提供的内核同步对象。
Semaphore semaphoreAcceptedClients = new Semaphore(2, 3,"Semaphore1");
解释一下意思:
第一个参数为:initialCount ,意指初始数量。Semaphore这个对象的使用是这么回事:在initialCoun设置为0的时候,WaitOne()方法会直接阻塞。至饿到它的Release方法被调用位置。但是如果initialCount>0,那么一开始便不会阻塞WaitOne方法N次。
第二个参数为maximumCount,即最大并发数。
第三个参数的话,我刚说它是操作系统的内核对象,那么又是可以用作跨进程线程同步的。
MSDN:http://msdn.microsoft.com/en-us/library/system.threading.semaphore(v=vs.110).aspx
举例:
using System; using System.Threading; 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."); } 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()); } }
跨进程的同步的话
A进程:
Semaphore semaphoreAcceptedClients = new Semaphore(2, 3,"Semaphore1");
B进程:
Semaphore semaphoreAcceptedClients2 = Semaphore.OpenExisting("Semaphore1");
使用和单进程中的线程同步一致。
完毕。