锁定还会锁定在锁定块内使用的变量吗? [英] Does locking also lock the variables which is being used inside the locked block?
本文介绍了锁定还会锁定在锁定块内使用的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class ThreadSafe
{
public static readonly object _locker = new object();
public static int _val1;
public int _val2 = 1;
public void Go()
{
lock (_locker)
{
if (_val2 != 0) Console.WriteLine (_val1 / _val2);
_val2 = 0;
}
}
}
在上面的示例中,另一个线程是否可以更改_val2和_val1的值?
In the above example is it possible for another thread to change the values of _val2 and _val1?
推荐答案
lock
关键字仅锁定对代码段的访问,而不能锁定对代码段的访问内部使用的数据.这意味着即使执行了锁定部分,另一个线程也可能同时修改_val1
和_val2
.
希望这会有所帮助,
弗雷德里克(Fredrik)
Thelock
keyword locks only access to the code section, not the data used inside of it. This means that it is possible for another thread to modify both_val1
and_val2
even when the locked section is executed.
Hope this helps,
Fredrik
这篇关于锁定还会锁定在锁定块内使用的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文