C#和布尔值的线程安全性 [英] C# and thread-safety of a bool

查看:251
本文介绍了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?

编辑

根据我所读的内容(

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#和布尔值的线程安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆