- Multithreading with C# Cookbook(Second Edition)
- Eugene Agafonov
- 385字
- 2021-07-09 19:35:37
Using the SemaphoreSlim construct
This recipe will show you how to limit multithreaded access to some resources with the help of the SemaphoreSlim
construct. SemaphoreSlim
is a lightweight version of Semaphore
; it limits the number of threads that can access a resource concurrently.
Getting ready
To step through this recipe, you will need Visual Studio 2015. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter2\Recipe3
.
How to do it...
To understand how to limit a multithreaded access to a resource with the help of the SemaphoreSlim
construct, perform the following steps:
- Start Visual Studio 2015. Create a new C# console application project.
- In the
Program.cs
file, add the followingusing
directives:using System; using System.Threading; using static System.Console; using static System.Threading.Thread;
- Below the
Main
method, add the following code snippet:static SemaphoreSlim _semaphore = new SemaphoreSlim(4); static void AccessDatabase(string name, int seconds) { WriteLine($"{name} waits to access a database"); _semaphore.Wait(); WriteLine($"{name} was granted an access to a database"); Sleep(TimeSpan.FromSeconds(seconds)); WriteLine($"{name} is completed"); _semaphore.Release(); }
- Inside the
Main
method, add the following code snippet: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(); }
- Run the program.
How it works...
When the main program starts, it creates a SemaphoreSlim
instance, specifying the number of concurrent threads allowed in its constructor. Then, it starts six threads with different names and start times to run.
Every thread tries to acquire access to a database, but we restrict the number of concurrent accesses to a database to four threads with the help of a semaphore. When four threads get access to a database, the other two threads wait until one of the previous threads finishes its work and signals to other threads by calling the _semaphore.Release
method.
There's more…
Here, we use a hybrid construct, which allows us to save a context switch in cases where the wait time is very short. However, there is an older version of this construct called Semaphore
. This version is a pure, kernel-time construct. There is no sense in using it, except in one very important scenario; we can create a named semaphore like a named mutex and use it to synchronize threads in different programs. SemaphoreSlim
does not use Windows kernel semaphores and does not support interprocess synchronization, so use Semaphore
in this case.
- 手機安全和可信應(yīng)用開發(fā)指南:TrustZone與OP-TEE技術(shù)詳解
- HornetQ Messaging Developer’s Guide
- 微服務(wù)設(shè)計(第2版)
- Visual Basic 6.0程序設(shè)計計算機組裝與維修
- HoloLens Beginner's Guide
- HTML5+CSS3基礎(chǔ)開發(fā)教程(第2版)
- BeagleBone Media Center
- 我的第一本算法書
- PHP網(wǎng)絡(luò)編程學(xué)習(xí)筆記
- JS全書:JavaScript Web前端開發(fā)指南
- Apache Mesos Essentials
- Android Native Development Kit Cookbook
- Java編程的邏輯
- ASP.NET Core 2 Fundamentals
- 詳解MATLAB圖形繪制技術(shù)