3 回答

TA貢獻(xiàn)1812條經(jīng)驗 獲得超5個贊
將信號量視為夜總會里的蹦蹦跳跳。一次有大量的人員被允許進(jìn)入俱樂部。如果俱樂部已滿,則不允許任何人進(jìn)入,但是一旦一個人離開,另一個人可能會進(jìn)入。
這只是限制特定資源使用者數(shù)量的一種方法。例如,限制同時調(diào)用應(yīng)用程序中的數(shù)據(jù)庫的次數(shù)。
這是C#中非常教學(xué)法的示例:-)
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace TheNightclub
{
public class Program
{
public static Semaphore Bouncer { get; set; }
public static void Main(string[] args)
{
// Create the semaphore with 3 slots, where 3 are available.
Bouncer = new Semaphore(3, 3);
// Open the nightclub.
OpenNightclub();
}
public static void OpenNightclub()
{
for (int i = 1; i <= 50; i++)
{
// Let each guest enter on an own thread.
Thread thread = new Thread(new ParameterizedThreadStart(Guest));
thread.Start(i);
}
}
public static void Guest(object args)
{
// Wait to enter the nightclub (a semaphore to be released).
Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
Bouncer.WaitOne();
// Do some dancing.
Console.WriteLine("Guest {0} is doing some dancing.", args);
Thread.Sleep(500);
// Let one guest out (release one semaphore).
Console.WriteLine("Guest {0} is leaving the nightclub.", args);
Bouncer.Release(1);
}
}
}

TA貢獻(xiàn)1799條經(jīng)驗 獲得超9個贊
Mutex:對資源的獨占成員訪問
信號量:對資源的n成員訪問
也就是說,互斥鎖可用于同步訪問計數(shù)器,文件,數(shù)據(jù)庫等。
一個sempahore可以做同樣的事情,但是支持固定數(shù)量的同時呼叫者。例如,我可以將數(shù)據(jù)庫調(diào)用包裝在semaphore(3)中,這樣我的多線程應(yīng)用程序最多可以同時連接3個數(shù)據(jù)庫。所有嘗試將阻塞,直到打開三個插槽之一。它們使像天真節(jié)流這樣的事情變得非常非常容易。
添加回答
舉報