C# and thread-safety of a bool

前端 未结 2 593
忘掉有多难
忘掉有多难 2020-12-09 16:14

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

    // case one, nothing
    private bool v1;
    public bool V         


        
2条回答
  •  鱼传尺愫
    2020-12-09 16:45

    No, not all of them are thread safe.

    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.

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

    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.

    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.)

提交回复
热议问题