C# 多线程系列之Mutex使用
互斥量是一个内核对象,它用来确保一个线程独占一个资源的访问,并且互斥量可以用于不同进程中的线程互斥访问资源。
我们可以把Mutex看作一个出租车,乘客看作线程。乘客首先等车,然后上车,最后下车。当一个乘客在车上时,其他乘客就只有等他下车以后才可以上车。而线程与C# Mutex对象的关系也正是如此,线程使用Mutex.WaitOne()方法等待C# Mutex对象被释放,如果它等待的C# Mutex对象被释放了,或者它没有被任何对象有用,它就自动拥有这个对象,直到它调用Mutex.ReleaseMutex()方法释放这个对象,而在此期间,其他想要获取这个C# Mutex对象的线程都只有等待。
Msdn地址:http://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx
举MSDN上的例子说明:
using System;
using System.Threading; class Example
{
// Create a new Mutex. The creating thread does not own the mutex.
private static Mutex mut = new Mutex();
private const int numIterations = ;
private const int numThreads = ; static void Main()
{
// Create the threads that will use the protected resource.
for(int i = ; i < numThreads; i++)
{
Thread newThread = new Thread(new ThreadStart(ThreadProc));
newThread.Name = String.Format("Thread{0}", i + );
newThread.Start();
} // The main thread exits, but the application continues to
// run until all foreground threads have exited.
} private static void ThreadProc()
{
for(int i = ; i < numIterations; i++)
{
UseResource();
}
} // This method represents a resource that must be synchronized
// so that only one thread at a time can enter.
private static void UseResource()
{
// Wait until it is safe to enter, and do not enter if the request times out.
Console.WriteLine("{0} is requesting the mutex", Thread.CurrentThread.Name);
if (mut.WaitOne()) {
Console.WriteLine("{0} has entered the protected area",
Thread.CurrentThread.Name); // Place code to access non-reentrant resources here. // Simulate some work.
Thread.Sleep(); Console.WriteLine("{0} is leaving the protected area",
Thread.CurrentThread.Name); // Release the Mutex.
mut.ReleaseMutex();
Console.WriteLine("{0} has released the mutex",
Thread.CurrentThread.Name);
}
else {
Console.WriteLine("{0} will not acquire the mutex",
Thread.CurrentThread.Name);
}
}
}
// The example displays output like the following:
// Thread1 is requesting the mutex
// Thread1 has entered the protected area
// Thread2 is requesting the mutex
// Thread3 is requesting the mutex
// Thread2 will not acquire the mutex
// Thread3 will not acquire the mutex
// Thread1 is leaving the protected area
// Thread1 has released the mutex
当一个线程占有Mutex后,代码就可以这样写:
mutex.WaitOne();
mutex.WaitOne();
mutex.WaitOne();
mutex.WaitOne();
。。
。。
WaitOne这个方法被调用时 系统检查发现mutex没有被任何线程使用 故而将mutex分配给当前线程
因而就算继续调用WaitOne也没有影响 因为系统发现当前线程已经占有 就直接返回了。换言之,waitOne是获取
Mutex锁的方式。如果调用ReleaseMutex那么当前线程退出Mutex锁,其它线程便可进来申请。但是如果调用两次
ReleaseMutex 那么由于当前线程实际上是不占有锁的 那么会抛出异常。
所以不能这样写:
mutex.ReleaseMutex();//如果已经占有 那么OK
mutex.ReleaseMutex();//调用第二次直接异常
Mutex是一个内核对象,所以,它是可以用作跨进程线程同步的。
A进程可以如此写:
Mutex mutex = new Mutex(true,"mutex1");
B进程则可以如此写:
Mutex mutex = Mutex.OpenExisting("mutex1")
OpenExisting这个方法签名我们后面也可以经常看到,作用就是获取一个已经存在的内核对象。
获取到之后的线程同步代码是跟单进程是一致的。
完毕。
C# 多线程系列之Mutex使用的更多相关文章
- Java多线程系列--“JUC锁”03之 公平锁(一)
概要 本章对“公平锁”的获取锁机制进行介绍(本文的公平锁指的是互斥锁的公平锁),内容包括:基本概念ReentrantLock数据结构参考代码获取公平锁(基于JDK1.7.0_40)一. tryAcqu ...
- Java多线程系列--“JUC锁”04之 公平锁(二)
概要 前面一章,我们学习了“公平锁”获取锁的详细流程:这里,我们再来看看“公平锁”释放锁的过程.内容包括:参考代码释放公平锁(基于JDK1.7.0_40) “公平锁”的获取过程请参考“Java多线程系 ...
- Java多线程系列--“JUC锁”05之 非公平锁
概要 前面两章分析了"公平锁的获取和释放机制",这一章开始对“非公平锁”的获取锁/释放锁的过程进行分析.内容包括:参考代码获取非公平锁(基于JDK1.7.0_40)释放非公平锁(基 ...
- Java多线程系列--“JUC锁”08之 共享锁和ReentrantReadWriteLock
概要 Java的JUC(java.util.concurrent)包中的锁包括"独占锁"和"共享锁".在“Java多线程系列--“JUC锁”02之 互斥锁Ree ...
- Java多线程系列
一.参考文献 1.:Java多线程系列目录 (一) 基础篇 01. Java多线程系列--“基础篇”01之 基本概念 02. Java多线程系列--“基础篇”02之 常用的实现多线程的两种方式 03. ...
- Java多线程系列--AQS之 LockSupport
concurrent包是基于AQS (AbstractQueuedSynchronizer)框架的,AQS(JAVA CAS原理.unsafe.AQS)框架借助于两个类: Unsafe(提供CAS操作 ...
- Java多线程系列--“JUC锁”10之 CyclicBarrier原理和示例
概要 本章介绍JUC包中的CyclicBarrier锁.内容包括:CyclicBarrier简介CyclicBarrier数据结构CyclicBarrier源码分析(基于JDK1.7.0_40)Cyc ...
- Java多线程系列--“JUC锁”02之 互斥锁ReentrantLock
本章对ReentrantLock包进行基本介绍,这一章主要对ReentrantLock进行概括性的介绍,内容包括:ReentrantLock介绍ReentrantLock函数列表ReentrantLo ...
- Java多线程系列--“JUC锁”01之 框架
本章,我们介绍锁的架构:后面的章节将会对它们逐个进行分析介绍.目录如下:01. Java多线程系列--“JUC锁”01之 框架02. Java多线程系列--“JUC锁”02之 互斥锁Reentrant ...
随机推荐
- System.Data.OracleClient.dll方式操作oracle数据库
System.Data.OracleClient.dll方式操作oracle数据库 一.查询语句: using (OracleConnection conn = new OracleConnectio ...
- lua 5.3 英文手册 自己收集整理版
/* ** state manipulation */ LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud);//创建lua虚拟机 LUA ...
- 面对对象二,super......反射
一.super() super() : 主动调用其他类的成员 # 单继承 # 在单继承中 super,主要是用来调用父类的方法的. class A: def __init__(self): self ...
- 解决wordcloud的一个error:Microsoft Visual C++ 9.0 is required. Get it from http://aka.ms/vcpython27
环境: 操作系统:Windows 7 64位 语言:Python 2.7.13 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:17:26) w ...
- PHP开发微信公众号(二)消息接受与推送
上一篇文章我们知道怎么获取二维码,这样别人就可以扫描二维码来关注我们,但是别人关注后,发送消息,我们怎么进行相关处理? 这里我们就来学习下怎么处理处理这些消息,以及推送消息. 学习之前首先你需要有一个 ...
- 编程开发之--Oracle数据库--存储过程使用动态参数绑定(3)
1.动态参数绑定,可以实现动态的执行不同的sql --创建包 create or replace PACKAGE MYPACKAGE AS type empcursor is ref cursor; ...
- nginx(三)-动静分离
什么叫动静分离 所谓动静分离就是说我们的图片,css,js之类的文件都交给nginx来处理,nginx处理不了的,比如jsp就交给tomcat来处理. 有人计算过,nginx代理处理静态请求远远优于t ...
- TP5.1 查看具体版本
https://blog.csdn.net/haibo0668/article/details/80865785 echo \think\facade\App::version(); composer ...
- Python——付费/版权歌曲下载
很多歌曲需要版权或者付费才能收听 正确食用方法: 1.找到歌曲编号 2.输入编号并点击下载歌曲 # coding:utf8 # author:Jery # datetime:2019/4/13 23: ...
- Linux云服务器下Tomcat部署
基于阿里云Centos 7服务器的Tomcat 项目部署 工具:一台安装jdk1.8的Centos 6/7.X 云服务器(64位) Putty ssh远程连接云服务器的软件 FileZillaCli ...