Use a Semaphore : Semaphore « Thread « C# / CSharp Tutorial

Home
C# / CSharp Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statement
5.String
6.struct
7.Class
8.Operator Overload
9.delegate
10.Attribute
11.Data Structure
12.Assembly
13.Date Time
14.Development
15.File Directory Stream
16.Preprocessing Directives
17.Regular Expression
18.Generic
19.Reflection
20.Thread
21.I18N Internationalization
22.LINQ
23.GUI Windows Forms
24.Windows Presentation Foundation
25.Windows Communication Foundation
26.Workflow
27.2D
28.Design Patterns
29.Windows
30.XML
31.XML LINQ
32.ADO.Net
33.Network
34.Directory Services
35.Security
36.unsafe
C# / C Sharp
C# / C Sharp by API
C# / CSharp Open Source
C# / CSharp Tutorial » Thread » Semaphore 
20.18.1.Use a Semaphore
using System;  
using System.Threading;  
 
class MyThread {  
  public Thread thrd; 
 
  static Semaphore sem = new Semaphore(22)
  
  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.
20.18.Semaphore
20.18.1.Use a Semaphore
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.