C#和布尔值的线程安全性

编程入门 行业动态 更新时间:2024-10-28 11:23:33
本文介绍了C#和布尔值的线程安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对此主题非常困惑-读取/切换布尔值是否是线程安全的.

I am very confused about this subject - whether reading/toggling a bool value is thread-safe.

// case one, nothing private bool v1; public bool V1 { get { return v1; } set { v1 = value; } } // case two, with Interlocked on set private int v2; public int V2 { get { return v2; } set { Interlocked.Exchange(ref v2, value); } } // case three, with lock on set private object fieldLock = new object(); private bool v3; public bool V3 { get { return v3; } set { lock (fieldLock) v3 = value; } }

它们都是线程安全的吗?

Are all of them thread-safe?

编辑

根据我所读的内容( click )布尔的原子性不能保证它是线程安全的.然后volatile键入帮助吗?

From what I have read (click) atomicity of bool does not guarantee it will be thread safe. Will then volatile type help?

推荐答案

不,并非所有线程安全.

No, not all of them are thread safe.

情况实际上并非完全是线程安全的,或者更好的说法是-根本不是线程安全的.即使使用布尔值进行的操作是原子的,变量值也可以存储在缓存中,因此,由于在多核CPU中每个内核都有自己的缓存,因此值可能会被破坏.

Case one isn't actually completely thread safe, or better saying - it isn't thread safe at all. Even if operations with boolean are atomic, variable value can be stored in a cache, and so, as in multicore CPU each core has it's own cache, value can be potentially corrupted.

更进一步,编译器和CPU可以执行一些内部优化,包括指令重新排序,这可能会有害地影响程序的逻辑.

Going even further, compiler and CPU can perform some internal optimizations, including instruction reordering, which can harmfully affect your program's logic.

您可以添加volatile关键字,以通知编译器该字段在多线程上下文中使用.它可以解决高速缓存和指令重新排序的问题,但不会给您真正的线程安全"代码(因为写操作仍将不同步).同样,volatile不能应用于局部变量.

You can add the volatile keyword, to notify the compiler that this field is used in a multi-threaded context. It will fix problems with cache and instruction reordering, but doesn't give you truly "thread safe" code (as write operations still will be not synchronized). Also volatile cannot be applied to local variable.

因此,在处理多线程时,您总是必须对有价值的资源使用某种线程同步技术.

So when dealing with multi-threading you always have to use some technique of thread synchronization on valuable resources.

有关更多信息,请阅读此答案,其中对不同技术进行了更深入的说明. (例如,有关于int的示例,但这并不重要,它描述了一般方法.)

For more information - read this answer, which has some deeper explanation of different techniques. (example there is about int, but is doesn't really matter, it describes general approach.)

更多推荐

C#和布尔值的线程安全性

本文发布于:2023-10-04 21:01:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467212.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   安全性   布尔值

发布评论

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

>www.elefans.com

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