架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 10234|回复: 0

[资料] lock为什么只能锁定引用不能锁定值类型

[复制链接]
发表于 2016-12-8 10:43:37 | 显示全部楼层 |阅读模式

他要的就是引用类型,如果你传一个值类型,会装箱,下次代码运行到这里,又会装箱,两次不是同一个对象,所以锁不住



lock(x)
{
  ...
}

实际是通过Monitor对象完成的锁:

上面等同于:

System.Object obj = (System.Object)x;
System.Threading.Monitor.Enter(obj);
try
{
  ...   
}
finally
{
  System.Threading.Monitor.Exit(obj);
}

进而引用msdn原话:
Use Monitor to lockobjects (that is, reference types), not value types. When you pass avalue type variable to Enter, it is boxed as an object. If you pass thesame variable to Enter again, it is boxed as a separate object, and thethread does not block. In this case, the code that Monitor issupposedly protecting is not protected. Furthermore, when you pass thevariable to Exit, still another separate object is created. Because theobject passed to Exit is different from the object passed to Enter,Monitor throws SynchronizationLockException. For more information, seethe conceptual topic Monitors.




上一篇:Centos 6.4系统升级Python2.6.6到2.7.5版本
下一篇:Directory.GetCurrentDirectory和Application.StartupPath的区别
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|手机版|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2024-4-19 02:48

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表