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 ...
随机推荐
- HTTP Error 500.0 - Internal Server Error错误代码0x80070002
案例研究:AspNetInitClrHostFailureModule中的“HTTP错误500.0 - 内部服务器错误” 症状 当用户访问在Windows Server 2008 R2计算机上运行的A ...
- LuoguP1032 字符变换(BFS)
题目链接为:https://www.luogu.org/problemnew/show/P1032 思路:看到数据比较小,而且最多有6个规则,就可以用搜索去做了,我用的BFS,大体思路如下: 定义结构 ...
- 在MyEclipse Tomcat可以运行但是在Tomcat 6.x上却不可以运行
- C函数指针的用法
1.最简单的用法: #include <cstdio> int (*p)(int);//定义一个函数指针变量p(下面的f其实是一个常量函数指针) int f(int x) { printf ...
- Inside Triangle
Inside Triangle https://hihocoder.com/contest/hiho225/problem/1 时间限制:10000ms 单点时限:1000ms 内存限制:256MB ...
- 128. Longest Consecutive Sequence最长连续序列
[抄题]: Given an unsorted array of integers, find the length of the longest consecutive elements seque ...
- SpringMVC工作原理1(基础机制)
图1.基本原理图 Spring工作流程描述 1. 用户向服务器发送请求,请求被Spring 前端控制Servelt DispatcherServlet捕获: 2. Dispat ...
- 【Spring】Spring boot多数据源历险记
一.问题描述 笔者根据需求在开发过程中,需要在原项目的基础上(单数据源),新增一个数据源C,根据C数据源来实现业务.至于为什么不新建一个项目,大概是因为这只是个小功能,访问量不大,不需要单独申请个服务 ...
- MySQL5.7.10配置和使用
前两天搞mybatis和springmvc的结合,搞了半天项目就是跑不起来,由于都没有接触过,也不知道原因出在哪里.今天想彻底学习下mybatis,于是就想使用MySQL.从官网上下了,MySQL-5 ...
- Golang之写一个聊天室
. 海量用户在线聊天系统 . 点对点聊天 . 用户登录&注册 一.服务端开发 . 用户管理 用户id:数字 用户密码:字母数字组合 用户昵称:用来显示 用户性别:字符串 用户头像:url 用户 ...