lock 和 Monitor (转载)
Lock和Monitor都是对被操作对象同步控制的方法
Lock 是 Monitor的简化版本,IL
callvirt ...Monitor.Enter(object)
...
leave.s
....
callvirt ...Monitor.Exit(object)
Lock 只能对引用对象加锁
Lock锁定区间内可以对锁定值修改而不发生运行时错误,通常也会采用此种修改方式。这种方式又有点类同于使用Monitor.Wait 取得资源,并对这个资源进行操作。
lock (lockObj)
{
lockObj = newObj;
}
Monitor 可以对值类型加锁,实际上是在调用Monitor.Enter时对值类型装箱了
Monitor在锁定区域内不能对被锁对象的值(不管是值类型还是引用类型)进行修改,运行时抱错“从不同步的代码块中调用了对象同步方法”
int lockInt = 0;
try
{
Monitor.Enter(lockInt);
lockInt = newValue;
}
catch
{
}
finally
{
Monitor.Exit(newValue);
}
Monitor 相对Lock有其他一些复杂功能
Monitor.TryEnter
//Try to add an element to the queue.
//Add the element to the queue only if the queue object is unlocked.
public bool AddElementWithoutWait(object qValue)
{
//Determine whether the queue is locked
if (!Monitor.TryEnter(m_inputQueue))
return false;
m_inputQueue.Enqueue(qValue);
Monitor.Exit(m_inputQueue);
return true;
}
//Try to add an element to the queue.
//Add the element to the queue only if during the specified time the queue object will be unlocked.
public bool WaitToAddElement(object qValue, int waitTime)
{
//Wait while the queue is locked.
if (!Monitor.TryEnter(m_inputQueue, waitTime))
return false;
m_inputQueue.Enqueue(qValue);
Monitor.Exit(m_inputQueue);
return true;
}
Monitor.Wait
Monitor.Pulse
Monitor.PulseAll
Monitor.Wait(m_smplQueue);
//Push one element.
m_smplQueue.Enqueue(counter);
//Release the waiting thread.
Monitor.Pulse(m_smplQueue);
Monitor.PulseAll(m_smplQueue);
Wait: 等待得到被锁对象,可以对被锁对象进行操作
Pulse: 释放当前锁定操作对象,下一个等待该对象的Wait将得到对象的使用权
PulseAll:释放当前锁定对象,所有正在等待该对象得Wait将同时得到释放(进入下一行代码,可以认为不在对该对象进行同步控制)
最新文章
- window上Python环境的搭建
- DataGridView 中CheckBox 获取状态
- runloop之于thread
- ArcGis API FOR Silverlight 做了个导航工具~
- scull_p_read()函数分析
- 文件末尾判断feof
- 微信小程序实现顶部、底部联动滑动
- 作为一个懒虫,如何优雅的使用windows
- 简单解析nestJS目录
- eclipse启动tomcat错误解决
- 15.2-uC/OS-III资源管理(信号量)
- LostRoutes项目日志——在main.js中添加多分辨率适配
- WinMain函数详解(转载再编辑)
- BZOJ4277 : [ONTAK2015]Cięcie
- 推荐一个 JavaScript 日期处理类库 Moment.js
- SAP SM13 V2更新队列批量执行
- java检验银行卡号
- Mac Sublime Vim模式 方向键无法长按
- mysql 5.6 windows7 解压缩版安装的坑
- 微软智能云的核心DNA
热门文章
- MyBatisPlus分页插件在SpringBoot中的使用
- 4.Future对象
- Codeforces 1672 E. notepad.exe
- GlusterFS常用维护操作命令
- Mysql综合实验2-LAMP+MHA+MYcat分库
- 有用的内置Node.js APIs
- Java多线程-线程生命周期(一)
- GY91(MPU9250 + BMP280)惯性传感器开发指南
- pagehelper使用有误导致sql多了一个limit
- 实战中的sudo提权漏洞的使用姿势(CVE-2021-3156)