C#多線程開發10:線程同步之Semaphore類

來源:互聯網
上載者:User

標籤:semaphore   semaphoreslim   訊號量   semaphore.wait   semaphore.release   

Semaphore類表示訊號量

訊號量和互斥類似,只是訊號量可以同時由多個線程使用,而互斥只能由一個線程使用。也就是說,使用訊號量時,可以多個線程同時訪問受保護的資源。下面執行個體示範了“學生到食堂就餐”的情境,一共有10個學生需要就餐,但是食堂每次只能接納4名學生就餐,所以將訊號量的計數設定為4,每次有4個任務(就餐任務)可以獲得鎖定。剩下的學生就必須等待,等到鎖定被解除時,學生才可以繼續獲得鎖定,進入食堂就餐。

using System;using System.Threading;using System.Threading.Tasks;namespace SemaphoreExample{    class Program    {        static void Main(string[] args)        {            int studentCount = 10;            int seatCount = 4;//小小食堂只有4個位子            var semaphore = new SemaphoreSlim(seatCount, seatCount);            var eatings = new Task[studentCount];            for (int i = 0; i < studentCount; i++)            {                eatings[i] = Task.Run(() => Eat(semaphore));             }            Task.WaitAll(eatings);            Console.WriteLine("All students have finished eating!");        }        static void Eat(SemaphoreSlim semaphore)        {            semaphore.Wait();            try            {                Console.WriteLine("Student {0} is eating now!", Task.CurrentId);                Thread.Sleep(1000);            }            finally            {                Console.WriteLine("Student {0} have finished eating!", Task.CurrentId);                semaphore.Release();            }        }    }}

代碼的執行結果如所示。

 

使用Semaphore類的執行個體方法Wait()鎖定訊號量,使用Release()方法可以解除鎖定。

.Net中訊號量有兩個類:Semaphore和SemaphoreSlim。Semaphore類可以命名,允許在不同進程之間同步。SemaphoreSlim類是對於較短等待時間進行了最佳化的輕型版本。本文中使用的是SemaphoreSlim類。

C#多線程開發10:線程同步之Semaphore類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.