锁定还会锁定在锁定块内使用的变量吗?

编程入门 行业动态 更新时间:2024-10-22 17:32:26
本文介绍了锁定还会锁定在锁定块内使用的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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) The lock 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

更多推荐

锁定还会锁定在锁定块内使用的变量吗?

本文发布于:2023-06-04 19:09:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/503363.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:还会   变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!