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. 表单跳转到Struts2

    在使用表单跳转到Struts2时,路径一直不正确. login.html如下: <form action="login.do" method=post> 账号:< ...

  2. 【MySQL报错】ERROR 1558 (HY000): Column count of mysql.user is wrong. Expected 43, found 39.

    原文参考:http://wuzhuti.cn/2348.html 之前在centos6.4系统安装的是自带的mysql 5.1版本,后来升级到了5.6版本,执行以下命令报错 在网上查找原因说说因为升级 ...

  3. Python3 tuple 函数

    Python3 tuple 函数  Python3 内置函数 描述 tuple 函数将列表转换为元组.. 语法 以下是 tuple 的语法: tuple( seq ) 参数 seq -- 要转换为元组 ...

  4. Median(二分+二分)

    Median http://poj.org/problem?id=3579 Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 1 ...

  5. 不使用if switch 各种大于 小于 判断2个数的大小

    哥们写的代码: dword big; __asm { mov eax,a mov ebx,b cmp eax,ebx jle HOHO big =ebx HOHO: big = eax } 网上搜了一 ...

  6. 提交代码到远程GIT仓库,代码自动同步到远程服务器上。

    现在一般都会通过github,gitlab,gitee来管理我们的代码.我们希望只要我本地push了代码,远程服务器能自动拉取git仓库的代码,进行同步. 这就需要用到各仓库为我们提供的webhook ...

  7. CentOS 安装 Xamarin官方Mono

    预先准备: 服务器可连入互联网 有yum 工具(没什么好说的,如果这个你没装,那重新装个系统吧,debian 等不要看这个,不一样的) wget 工具(可选) yum-uitl 工具包 导入Xamar ...

  8. SSH框架整合jar包时的注意事项

    SSH框架整合jar包时的注意事项: 在将三个框架所需的jar整合到一起后,要看一下有没有相同类型但是版本不同的jar包,如果有的话,需要把低版本的jar包删除掉,否则会报错.我这里整合的时候java ...

  9. 2015湖南湘潭 D 二分

    2015湖南湘潭第七届大学生程序设计比赛 D题 Fraction Accepted : 133   Submit : 892 Time Limit : 1000 MS   Memory Limit : ...

  10. CString 作为参数执行都不执行

    static int LoadUsbSDK(CString curpath ) win10系统下 CString 函数加载dll直接跳过 加载dll最好不要带参数