C#多線程那點事——訊號量(Semaphore)

來源:互聯網
上載者:User

訊號量說簡單點就是為了線程同步,或者說是為了限制線程能啟動並執行數量。

那它又是怎麼限制線程的數量的哩?是因為它內部有個計數器,比如你想限制最多5個線程運行,那麼這個計數器的值就會被設定成5,如果一個線程調用了這個Semaphore,那麼它的計數器就會相應的減1,直到這個計數器變為0。這時,如果有另一個線程繼續調用這個Semaphore,那麼這個線程就會被阻塞。

獲得Semaphore的線程處理完它的邏輯之後,你就可以調用它的Release()函數將它的計數器重新加1,這樣其它被阻塞的線程就可以得到調用了。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Semaphore1
{
class Program
{
//我設定一個最大允許5個線程允許的訊號量
//並將它的計數器的初始值設為0
//這就是說除了調用該訊號量的線程都將被阻塞
static Semaphore semaphore = new Semaphore(0, 5);

static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
Thread thread = new Thread(new ParameterizedThreadStart(work));

thread.Start(i);
}

Thread.Sleep(1000);
Console.WriteLine("Main thread over!");

//釋放訊號量,將初始值設回5,你可以將
//將這個函數看成你給它傳的是多少值,計數器
//就會加多少回去,Release()相當於是Release(1)
semaphore.Release(5);
}

static void work(object obj)
{
semaphore.WaitOne();

Console.WriteLine("Thread {0} start!",obj);

semaphore.Release();
}
}
}

 

結果如所示,其它的線程只有等到主線程釋放才會執行,因為我給訊號量計數器的初始值是0,所以其它線程在主線程釋放前都會被阻塞。而後,我在主線程直接用Release()函數將計數器置為5,所以5個線程可以同時得到執行。

 

另外,可以給訊號量設定一個名稱,這個名稱是作業系統可見的,因此,可以使用這些訊號量來協調跨進程邊界的資源使用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Semaphore2
{
class Program
{
static void Main(string[] args)
{
Semaphore seamphore = new Semaphore(5, 5, "SemaphoreExample");

seamphore.WaitOne();
Console.WriteLine("Seamphore 1");
seamphore.WaitOne();
Console.WriteLine("Seamphore 2");
seamphore.WaitOne();
Console.WriteLine("Seamphore 3");

Console.ReadLine();
seamphore.Release(3);
}
}
}

 

運行兩個這樣的程式,你講看到這樣的結果,在第二個啟動並執行樣本中,會將線程阻塞在第三個訊號量上。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.