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 ...
随机推荐
- mysql 数值与字符类型 长度梳理
上述表格中的数值类型都是定长的,也就是说,无论你存的数值是多少,多大或者多小,占用的存储字节大小都是固定的.例如,设置int(1),虽然M值是1个字符,但是它所占用的空间大小永远都是4个字节的大小,换 ...
- sharepoint 调查问卷权限设置
参考网址:http://www.cnblogs.com/mybi/archive/2011/04/18/2019935.html 按文章设置后发现访问时提示没有权限. 于是把新权限(问卷回复)的权限组 ...
- 85. Maximal Rectangle (Graph; Stack, DP)
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and ...
- 探讨 .NET 4 新增的 SortedSet 类
http://www.cnblogs.com/WizardWu/archive/2010/06/17/1759297.html
- Petya and Graph(最小割,最大权闭合子图)
Petya and Graph http://codeforces.com/contest/1082/problem/G time limit per test 2 seconds memory li ...
- 模块常用snippet
压缩,文件操作,数据库,md5,json, 压缩 import os, sys, time import zipfile # 解压 filename = 'callofdutyblackopszomb ...
- Git Submodule 使用简介
参考http://www.diguage.com/archives/146.html 一.添加子模块 从新建一个项目,或者从远处服务器上克隆一个项目,作为“顶级项目”.这里,从 Github 上新建一 ...
- linux系统命令笔记
一.linux系统目录 /bin 系统命令目录 /dev 设备目录 /home 每个系统用户在home下都有一个目录, 每个用户登录到系统后会自动登录到这个目录下, root用户会在/root文件夹下 ...
- Vue.js (Frontend & Backend)尝试前后端分离
前言 前端用什么框架都可以,这里选择小巧的vuejs. 要实现的功能很简单:1.登录功能,成功将服务器返回的token存在本地2.使用带token的header访问服务器的一个资源 本次实验环境: & ...
- JDK和Eclipse的下载路径
JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html Eclipse http://www.eclipse.or ...