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:

WaitHandle Class

Overview of Synchronization Primitives

AutoResetEvent Class

ManualResetEvent Class

Thread in depth 4:Synchronous primitives的更多相关文章

  1. Thread in depth 3:Synchronization

    Synchronization means multi threads access the same resource (data, variable ,etc) should not cause ...

  2. 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 ...

  3. Thread in depth 1: The basic

    Every single thread has the follow elements: Execution Context:Every thread has a execution context ...

  4. redis-4.0.8 配置文件解读

    # Redis configuration file example.## Note that in order to read the configuration file, Redis must ...

  5. docker+redis安装与配置,主从+哨兵模式

    docker+redis安装与配置 docker安装redis并且使用redis挂载的配置启动 1.拉取镜像 docker pull redis:3.2 2.准备准备挂载的目录和配置文件 首先在/do ...

  6. 009-docker-安装-redis:5.0.3

    1.搜索镜像 docker search redis 2.拉取合适镜像 docker pull redis:5.0.3 docker images 3.使用镜像 docker run -p 6379: ...

  7. 16、Redis手动创建集群

    写在前面的话:读书破万卷,编码如有神 --------------------------------------------------------------------------------- ...

  8. 14、Redis的复制

    写在前面的话:读书破万卷,编码如有神 --------------------------------------------------------------------------------- ...

  9. redis sentinels哨兵集群环境配置

    # Redis configuration file example. # # Note that in order to read the configuration file, Redis mus ...

随机推荐

  1. zg项目 应用系统编码原则

    一.编码说明: 1.系统编码采用三码为原则,通常两码简称之. 1>.子系统或类型 2>.系统小分类 3>.系统大分类 如 IPMS领域业务群: DA 应用软件发展管理系统 DE公用副 ...

  2. 根据数组下标在MongoDB中修改数组元素

    如下图这样的数据: 即文档中某个字段是一个数组,而每个数组元素又是一个对象,现在需求是对每个对象中的content字段值作情感分析后,把情感分析得到的结果增加到这个对象中去. 如上图中第1个元素,修改 ...

  3. Educational Codeforces Round 58

    D. GCD Counting 题意: 给出n个点的树,每个点有一个权值,找出一条最长的路径使得路径上所有的点的gcd>1 题解: gcd>1的一定不会有很多.所以暴力搞一下就行,不需要点 ...

  4. RigidBody组件的Is Kinematic

    RigidBody组件的Is Kinematic属性打上勾(设为true,使其不受物理引擎驱动,Wall是为了防止其移动,Person是为了防止其受到力不断旋转—看的心塞=v=) .is kinema ...

  5. 【校招面试 之 剑指offer】第10-3题 矩阵覆盖问题

    题目:我们可以使用2✖️1的小矩形横着或者竖着去覆盖更大的矩形.请问用8个2✖️1的小矩形无重叠地覆盖一个2✖️8的大矩形,共有多少种方法? 分析:当放第一块时(假定从左边开始)可以横着放,也可以竖着 ...

  6. ROS两种workspace :overlay rosbuild_ws->catkin_ws->ROS库,

    概念 ROS里面有一系列概念,作为初学者,最先接触的概念无非是node, package和workspace. node node是ROS里面最小的执行单位,你可以把node看成是一个main函数,当 ...

  7. SVN的标准目录结构:trunk、branches、tags

    原文链接:http://techlife.blog.51cto.com/212583/223704/ 我们在一些著名开源项目的版本库中,通常可以看到trunk, branches, tags等三个目录 ...

  8. Spring框架的事务管理之声明式事务管理的类型

    1. 声明式事务管理又分成两种方式 * 基于AspectJ的XML方式(重点掌握)(具体内容见“https://www.cnblogs.com/wyhluckdog/p/10137712.html”) ...

  9. js手机号码正则表达式

    function checkMobile(){ var sMobile = document.mobileform.mobile.value if(!(/^1[3|4|5|8][0-9]\d{4,8} ...

  10. 建表Table

    Sstudent表   学  号    Sno  姓  名   Sname   性  别    Ssex     年  龄      Sage   所 在 系    Sdept   200215121 ...