线程同步-使用SimaphoreSlim类

SimaphoreSlim类是作为Semaphore类的轻量级版本的。该类限制了同时访问同一个资源的线程数量。

代码Demo:

using System;
using System.Threading;

在Main方法下面加入以下代码片段:

 static SemaphoreSlim _semaphore = new SemaphoreSlim(4);------1

static void AccessDatabase(string name, int seconds)
{
Console.WriteLine("{0} waits to access a database", name);
_semaphore.Wait();
Console.WriteLine("{0} was granted an access to a database", name);
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine("{0} is completed", name);
_semaphore.Release();
}

在Main方法中加入以下代码片段:

for (int i = 1; i <= 6; i++)
{
 string threadName = "Thread" + i;
 int secondsToWait = 2 + 2 * i;
 var t = new Thread(() => AccessDatabase(threadName, secondsToWait));
 t.Start();
}

工作原理:

主线程启动时,创建了SemaphoreSlim的一个实例,并在其构造函数中制定允许的并发线程数量(1行所示)。然后启动了6个不同名称和不同初始运动时间的线程。

每个线程都尝试获取数据库的访问,但是我们借助于信号系统限制了访问数据库的并发数为4个线程。当有4个线程获取了数据库的访问后,其它两个线程需要等待,知道之前线程中的某一个完成工作并调用_semaphore.Release方法来发出信号。

posted @ 2018-07-03 20:39  v-haoz  阅读(84)  评论(0编辑  收藏  举报