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

多线程的并发控制

时间:2019-01-23 12:32:52      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:current   访问   总线   oid   线程   task   多个   eating   for   

  当有多个线程同时访问有限制的资源时会出现并发情况,此时可以使用‘信号量’来控制访问资源的线程数量


        static void Main(string[] args)
         {

                int taskCount = 10;//总线程数
                 int seatCount = 4;//资源访问最大线程数量
                 var semaphore = new SemaphoreSlim(seatCount,6);
                 var tasks = new Task[taskCount];
                 for (int i = 0; i < taskCount; i++)
                 {
                     tasks[i] = Task.Run(() => TaskRun(semaphore));
                 }
                 Task.WaitAll(eatings);
                 Console.WriteLine("All Tasks have finished!");
         }
         static void TaskRun(SemaphoreSlim semaphore)
         {
             semaphore.Wait();
             try
             {
                 Console.WriteLine("Task {0} is Running!", Task.CurrentId);
                 Thread.Sleep(1000);
             }
             finally
             {
                 Console.WriteLine("Task {0} have finished!", Task.CurrentId);
                 semaphore.Release();
             }
         }

多线程的并发控制

标签:current   访问   总线   oid   线程   task   多个   eating   for   

原文地址:https://www.cnblogs.com/getpower/p/10308129.html

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