Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Semaphore ใน C#

คลาส Semaphore จำกัดจำนวนเธรดที่เข้าถึง Critical Section ใช้ควบคุมการเข้าถึง Resource Pool อยู่ใน namespace System.Threading

Constructor หลัก:

ลำดับConstructor & Description
1Semaphore(Int32,Int32) - ระบุจำนวนเริ่มต้นและสูงสุดของเธรดที่เข้าถึงได้พร้อมกัน
2Semaphore(Int32,Int32,String) - เพิ่มชื่อ System Semaphore Object
3Semaphore(Int32,Int32,String,Boolean) - เพิ่มตัวแปรรับค่าว่าสร้างใหม่หรือไม่

ตัวอย่างใช้ new Semaphore(2, 2) อนุญาต 2 เธรดพร้อมกัน

ตัวอย่าง

using System;
using System.Threading;
namespace Program {
    class Demo {
        static Thread[] t = new Thread[5];
        static Semaphore semaphore = new Semaphore(2, 2);
        static void DoSomething() {
            Console.WriteLine("{0} = waiting", Thread.CurrentThread.Name);
            semaphore.WaitOne();
            Console.WriteLine("{0} begins!", Thread.CurrentThread.Name);
            Thread.Sleep(1000);
            Console.WriteLine("{0} releasing...", Thread.CurrentThread.Name);
            semaphore.Release();
        }
        static void Main(string[] args) {
            for (int j = 0; j < 5; j++) {
                t[j] = new Thread(DoSomething);
                t[j].Name = "thread number " + j;
                t[j].Start();
            }
            Console.Read();
        }
    }
}

ผลลัพธ์

thread number 2 = waiting
thread number 0 = waiting
thread number 3 = waiting
thread number 1 = waiting
thread number 4 = waiting
thread number 2 begins!
thread number 1 begins!
thread number 2 releasing...
thread number 1 releasing...
thread number 4 begins!
thread number 3 begins!
thread number 4 releasing...
thread number 0 begins!
thread number 3 releasing...
thread number 0 releasing...