猿问
什么是信号量?
信号量是一种编程概念,经常用于解决多线程问题。我对社区的问题:
什么是信号量,如何使用?
德玛西亚99
浏览 426
回答 3
3回答
智慧大石
将信号量视为夜总会里的蹦蹦跳跳。一次有大量的人员被允许进入俱乐部。如果俱乐部已满,则不允许任何人进入,但是一旦一个人离开,另一个人可能会进入。这只是限制特定资源使用者数量的一种方法。例如,限制同时调用应用程序中的数据库的次数。这是C#中非常教学法的示例:-)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); } }}
0
0
0
繁华开满天机
Mutex:对资源的独占成员访问信号量:对资源的n成员访问也就是说,互斥锁可用于同步访问计数器,文件,数据库等。一个sempahore可以做同样的事情,但是支持固定数量的同时呼叫者。例如,我可以将数据库调用包装在semaphore(3)中,这样我的多线程应用程序最多可以同时连接3个数据库。所有尝试将阻塞,直到打开三个插槽之一。它们使像天真节流这样的事情变得非常非常容易。
0
0
0
随时随地看视频
慕课网APP
相关分类
算法与数据结构
数据结构中,与所使用的计算机无关的数据是什么?
1 回答
学完C语言之后是先学数据结构还是先学JAVA好呢?
1 回答
我要回答