This article is a mirror article of machine translation, please click here to jump to the original article.

View: 18907|Reply: 0

[Source] lock Why can only lock the reference but not the value type

[Copy link]
Posted on 12/8/2016 10:43:37 AM | | |

If you pass a value type, it will be boxed, and the next time the code runs here, it will be boxed again, and it will not be the same object twice, so it cannot be locked



lock(x)
{
  ...
}

The lock is actually done through the Monitor object:

The above is equivalent to:

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

Then to quote the original words of 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.




Previous:Upgrade Python 2.6.6 to 2.7.5 on Centos 6.4 system
Next:Difference between Directory.GetCurrentDirectory and Application.StartupPath
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com