Thread in depth 4:Synchronous primitives
There are some synchronization primitives in .NET used to achieve thread synchronization
Monitor
c# provides System.Threading.Monitor class which cooperates with an objcet to implement locking. Every object has a sync block inside its data stucture,which used by the Monitor to mark down if it is referenced by one thread .The lock statement in c# is implemented by Monitor,and it uses try...catch..finally block to ensure the lock will be released even exception occurs.
Knowing Monitor uses sync block of a object to implement thread locking is helpful to understand the behavior of the lock statement.The figure below describes what happens when using lock statement.

Mutex
The System.Threading.Mutex class derives from System.Threading.WaitHandle class,so Threads request a mutex by calling its WaitOne method, and it provides some overloads to WaitOne method supporting the timeout of waitting.In addition,you can also use the WaitAll,WaitAny or SignalAndWait methods
SpinLock
C# provides a System.Threading.SpinLock class to implement the spin locking. Spin Lock means it will let the thread keep running in loop until it has the access permission to the resource.In most time,OS uses kernel wait handle to block the thread if use synchronous primitives which derives from WaitHandle,like semaphore and WaitEvent class, that means the execution will go through from the managed code and native kernel method, this will bring a performance issue.However, if the lock is held for a very short time,then let the thread run in loop will have a better performance.Of course, keep the thread running can cause a thread context switch and an occupation to CPU, so think twise before using it.
Semaphore
The System.Threading.Semaphore derives from WaitHandle,so can use WaitOne method or WaitAny,WaitAll static method just like Mutex class ,and it allows a specified number of threads to access a resourceIn addional, you can specify a name to a semaphore, a semaphore won't block another thread which has a semaphore of a different name.check the codes below:
public class SyncSample
{
public void DoWork()
{
Semaphore s = new Semaphore(, , "name_of_semaphore");
s.WaitOne();
Console.WriteLine("doing work");
Thread.Sleep();
Console.WriteLine("work done");
s.Release();
}
}
class Program
{
static void Main(string[] args)
{
SyncSample sc = new SyncSample();
Task.Run(() => { sc.DoWork(); });
Task.Run(() => { sc.DoWork(); });
Console.Read();
}
}
The result is:

If we specify another name, no thread will be blocked:
public class SyncSample
{
public void DoWork()
{
Semaphore s = new Semaphore(, , Guid.NewGuid().ToString());//will get a different name here
s.WaitOne();
Console.WriteLine("doing work");
Thread.Sleep();
Console.WriteLine("work done");
s.Release();
}
}
class Program
{
static void Main(string[] args)
{
SyncSample sc = new SyncSample();
Task.Run(() => { sc.DoWork(); });
Task.Run(() => { sc.DoWork(); });
Console.Read();
}
}
The result is:

EventWaitHandle
[MSDN]System.Threading.EventWaitHandle class threads to communicate with each other by signaling.Typically,one or more threads block on an EventWaitHandle until an unblocked thread calls the Set method,releasing one or more of the blocked threads.A thread can signal an EventWaitHandle and then block on it,by calling the static WaitHandle.SignalAndWait method.
The constructor accepts an initialState parameter,indicating the initial state of the EventWaitHandler:true then signaled and false is nonsignaled.
The other parameter you can pass into the constructor is EventResetMode enum,being used to controll the behavior of the EventWaitHandle to be AutoReset or ManualRest.AutoRest means the EventWaitHandler is just like a fitting room that has a signal light indicating if it is available or not.When a person gets into the room, the signal light will be off automatically, when the person gets out,the signal light will be turned on automatically ,waitting another person to get in. On the other hand,ManualRest means the EventWaitHandle is like a gate of the zoo, if the admin open the gate ,ALL waitting people rush into the zoo, until the admin close the gate again, then others people who not yet get into the zoo have to wait for the gate open again.
See also:
Overview of Synchronization Primitives
Thread in depth 4:Synchronous primitives的更多相关文章
- Thread in depth 3:Synchronization
Synchronization means multi threads access the same resource (data, variable ,etc) should not cause ...
- Thread in depth 2:Asynchronization and Task
When we want to do a work asynchronously, creating a new thread is a good way. .NET provides two oth ...
- Thread in depth 1: The basic
Every single thread has the follow elements: Execution Context:Every thread has a execution context ...
- redis-4.0.8 配置文件解读
# Redis configuration file example.## Note that in order to read the configuration file, Redis must ...
- docker+redis安装与配置,主从+哨兵模式
docker+redis安装与配置 docker安装redis并且使用redis挂载的配置启动 1.拉取镜像 docker pull redis:3.2 2.准备准备挂载的目录和配置文件 首先在/do ...
- 009-docker-安装-redis:5.0.3
1.搜索镜像 docker search redis 2.拉取合适镜像 docker pull redis:5.0.3 docker images 3.使用镜像 docker run -p 6379: ...
- 16、Redis手动创建集群
写在前面的话:读书破万卷,编码如有神 --------------------------------------------------------------------------------- ...
- 14、Redis的复制
写在前面的话:读书破万卷,编码如有神 --------------------------------------------------------------------------------- ...
- redis sentinels哨兵集群环境配置
# Redis configuration file example. # # Note that in order to read the configuration file, Redis mus ...
随机推荐
- Web标准:七、横向导航菜单
Web标准:七.横向导航菜单 知识点: 1.横向列表菜单 2.用图片美化的横向导航 3.css Sprites 1)横向列表菜单 可以在第四节课的基础上来实现横向导航菜单,只要给li一个float ...
- hdoj Max Sum Plus Plus(DP)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1024 题意:----最大M子段和问题给定由 n个整数(可能为负整数)组成的序列a1,a2,a3,……, ...
- rubber
rubber - 必应词典 美['rʌbər]英['rʌbə(r)] n.橡胶:橡皮:黑板擦 v.涂橡胶于…:〈美俚〉同“rubberneck” 网络橡皮擦:胶皮:橡皮轮胎 变形复数:rubbers:
- c++继承赋值兼容
其实还是不明白,红色部分,,,求解 #include <iostream>#include <time.h>using namespace std; class B0{publ ...
- 安装Oracle客户端寻找配置文件tnsnames.ora
# tnsnames.ora Network Configuration File: D:\app\Administrator\product\11.2.0\dbhome_1\network\admi ...
- [leetcode]496. Next Greater Element I下一个较大元素
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of n ...
- datagridview 如何禁止行被选中
如题,如何规定特定的行,光标不能定位,也不能被选中,就好想Button中的Enable属性那样,变灰,而且点击也没有反应那种,这样的效果,如何实现. datagridview [解决办法]dataGr ...
- Object类中通用方法之:toString()方法
1.Java所有的对象都是Object类的实例,都可以直接调用该类中定义的方法,这些方法称为通用方法 2.toString()方法即为Object类中定义的通用方法之一 3.平时我们如果在控制台直接打 ...
- WinScp获取一个文件
CD /d C:\Program Files (x86)\WinSCPWinSCP.exe /console /command "option batch continue" &q ...
- phoenix错误
spark集群与phoenix进行数据请求时报错: 2018-06-15 17:13:30,158 INFO - Starting task 15.3 in stage 116.0 (TID 6832 ...