码迷,mamicode.com
首页 > 编程语言 > 详细

C#多线程---Semaphore实现线程同步

时间:2018-09-15 16:32:39      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:span   初始   col   sys   can   mit   多线程   system   eth   

一、简介

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 Program
11     {
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<int> task = new Task<int>(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             else
34             {
35                 Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} get semaphore failed!");
36             }
37           
38             return sum;
39         }
40     }
41 }
View Code

运行结果如下:
技术分享图片

C#多线程---Semaphore实现线程同步

标签:span   初始   col   sys   can   mit   多线程   system   eth   

原文地址:https://www.cnblogs.com/3xiaolonglong/p/9651064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!