您好,欢迎访问一九零五行业门户网

C#多线程之Semaphore的使用详解

这篇文章主要为大家详细介绍了c#多线程之semaphore用法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
semaphore:可理解为允许线程执行信号的池子,池子中放入多少个信号就允许多少线程同时执行。
private static void multithreadsynergicwithsemaphore() { //0表示创建semaphore时,拥有可用信号量数值 //1表示semaphore中,最多容纳信号量数值 semaphore semaphore = new semaphore(0, 1); thread thread1 = new thread(() => { //线程首先waitone等待一个可用的信号量 semaphore.waitone(); //在得到信号量后,执行下面代码内容 console.writeline("thread1 work"); thread.sleep(5000); //线程执行完毕,将获得信号量释放(还给semaphore) semaphore.release(); }); thread thread2 = new thread(() => { semaphore.waitone(); console.writeline("thread2 work"); thread.sleep(5000); semaphore.release(); }); thread2.start(); thread1.start(); //因在创建semaphore时拥有的信号量为0 //semaphore.release(1) 为加入1个信号量到semaphore中 semaphore.release(1); }
说明:
1、如果semaphore.release(n),n>semaphore最大容纳信号量,将出异常。
2、当semaphore拥有的信号量为1时,semaphore相当于mutex
3、当semaphore拥有的信号量>1时,信号量的数量即可供多个线程同时获取的个数,此时可认为获取到信号量的线程将同时执行(实际情况可能与cpu核心数、cpu同时支出线程数有关)
以上就是c#多线程之semaphore的使用详解的详细内容。
其它类似信息

推荐信息