博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#多线程---Semaphore实现线程同步
阅读量:4511 次
发布时间:2019-06-08

本文共 1481 字,大约阅读时间需要 4 分钟。

一、简介

Semaphore类限制可同时访问某一资源或资源池的线程数线程通过调用 WaitOne方法将信号量减1,并通过调用 Release方法把信号量加1。

构造函数:public Semaphore(int initialCount,int maximumCount);通过两个参数来设置信号的初始计数和最大计数。

二、例子

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 using System.Threading.Tasks; 7  8 namespace ThreadMutex 9 {10     class Program11     {12         private static Mutex mutex = new Mutex();13         private static Semaphore semaphore = new Semaphore(3, 10);14         private static int sum = 0;15         static void Main(string[] args)16         {17             for (int i = 0; i < 10; i++)18             {19                 Task
task = new Task
(ThreadFunction);20 task.Start();21 }22 Console.WriteLine($"{DateTime.Now} task started!");23 Console.Read();24 25 }26 private static int ThreadFunction()27 {28 Thread.Sleep(100);29 if(semaphore.WaitOne(2000))30 {31 Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} get semaphore successed!");32 }33 else34 {35 Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} get semaphore failed!");36 }37 38 return sum;39 }40 }41 }
View Code

运行结果如下:

转载于:https://www.cnblogs.com/3xiaolonglong/p/9651064.html

你可能感兴趣的文章
php count函数
查看>>
PHP 跨域问题 (转)
查看>>
TFG液晶 字符模块
查看>>
Python2和Python3语法区别
查看>>
SQL Server 触发器
查看>>
Ural 1146 Maximum Sum(DP)
查看>>
《STL源代码分析》---stl_stack.h读书笔记
查看>>
UVA 10385 - Duathlon(三分法)
查看>>
div同时使用两个class
查看>>
在路上,三线城市互联网创业记录
查看>>
spark 编译遇到的错误及解决办法(五)
查看>>
框架篇: React + React-Router + antd + nodejs + express框架开发运用(nodejs做前后端server)...
查看>>
8、使用转换流处理标准输入
查看>>
Git 常用命令
查看>>
Why does Http header contains "X-SourceFiles"?
查看>>
uva 10976 fractions again(水题)——yhx
查看>>
爬虫实战篇---数据入库之去重与数据库
查看>>
CMPSC-132 – Programming and Computation
查看>>
RazorPad中的ModelProvider
查看>>
用于 Visual Studio 和 ASP.NET 的 Web 应用程序项目部署常见问题
查看>>