Csharp/CSharp Tutorial/Thread/Semaphore

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Use a Semaphore

using System;  
using System.Threading;  
 
class MyThread {  
  public Thread thrd; 
 
  static Semaphore sem = new Semaphore(2, 2); 
  
  public MyThread(string name) {  
    thrd = new Thread(this.run);  
    thrd.Name = name;  
    thrd.Start();  
  }  
  
  void run() {  
    Console.WriteLine(thrd.Name + " is waiting for a permit."); 
 
    sem.WaitOne(); 
 
    Console.WriteLine(thrd.Name + " acquires a permit."); 
 
    for(int i=0;i<10;i++) { 
      Console.WriteLine(thrd.Name + " : " + i); 
      Thread.Sleep(50);  
    } 
  
    Console.WriteLine(thrd.Name + " releases a permit."); 
 
    sem.Release(); 
  }  
}  
 
  
class MainClass {  
  public static void Main() {  
    MyThread mt1 = new MyThread("Thread #1");  
    MyThread mt2 = new MyThread("Thread #2");  
    MyThread mt3 = new MyThread("Thread #3");  
  
    mt1.thrd.Join(); 
    mt2.thrd.Join(); 
    mt3.thrd.Join(); 
  }  
}
Thread #1 is waiting for a permit.
Thread #1 acquires a permit.
Thread #1 : 0
Thread #2 is waiting for a permit.
Thread #2 acquires a permit.
Thread #2 : 0
Thread #3 is waiting for a permit.
Thread #1 : 1
Thread #2 : 1
Thread #1 : 2
Thread #2 : 2
Thread #1 : 3
Thread #2 : 3
Thread #2 : 4
Thread #1 : 4
Thread #2 : 5
Thread #1 : 5
Thread #2 : 6
Thread #1 : 6
Thread #1 : 7
Thread #2 : 7
Thread #1 : 8
Thread #2 : 8
Thread #1 : 9
Thread #2 : 9
Thread #1 releases a permit.
Thread #3 acquires a permit.
Thread #3 : 0
Thread #2 releases a permit.
Thread #3 : 1
Thread #3 : 2
Thread #3 : 3
Thread #3 : 4
Thread #3 : 5
Thread #3 : 6
Thread #3 : 7
Thread #3 : 8
Thread #3 : 9
Thread #3 releases a permit.