什么是信号量?

信号量是一种编程概念,经常用于解决多线程问题。我对社区的问题:

什么是信号量,如何使用?


德玛西亚99
浏览 388回答 3
3回答

智慧大石

将信号量视为夜总会里的蹦蹦跳跳。一次有大量的人员被允许进入俱乐部。如果俱乐部已满,则不允许任何人进入,但是一旦一个人离开,另一个人可能会进入。这只是限制特定资源使用者数量的一种方法。例如,限制同时调用应用程序中的数据库的次数。这是C#中非常教学法的示例:-)using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace TheNightclub{&nbsp; &nbsp; public class Program&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public static Semaphore Bouncer { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public static void Main(string[] args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Create the semaphore with 3 slots, where 3 are available.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Bouncer = new Semaphore(3, 3);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Open the nightclub.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; OpenNightclub();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public static void OpenNightclub()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i <= 50; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Let each guest enter on an own thread.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread thread = new Thread(new ParameterizedThreadStart(Guest));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; thread.Start(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public static void Guest(object args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Wait to enter the nightclub (a semaphore to be released).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Bouncer.WaitOne();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Do some dancing.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Guest {0} is doing some dancing.", args);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.Sleep(500);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Let one guest out (release one semaphore).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Guest {0} is leaving the nightclub.", args);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Bouncer.Release(1);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

繁华开满天机

Mutex:对资源的独占成员访问信号量:对资源的n成员访问也就是说,互斥锁可用于同步访问计数器,文件,数据库等。一个sempahore可以做同样的事情,但是支持固定数量的同时呼叫者。例如,我可以将数据库调用包装在semaphore(3)中,这样我的多线程应用程序最多可以同时连接3个数据库。所有尝试将阻塞,直到打开三个插槽之一。它们使像天真节流这样的事情变得非常非常容易。
打开App,查看更多内容
随时随地看视频慕课网APP