Do I need to use locking with integers in c++ threads

前端 未结 7 1471
慢半拍i
慢半拍i 2021-01-04 21:10

If I am accessing a single integer type (e.g. long, int, bool, etc...) in multiple threads, do I need to use a synchronisation mechanism such as a mutex to lock them. My un

7条回答
  •  鱼传尺愫
    2021-01-04 21:31

    In 99.99% of the cases, you must lock, even if it's access to seemingly atomic variables. Since C++ compiler is not aware of multi-threading on the language level, it can do a lot of non-trivial reorderings.

    Case in point: I was bitten by a spin lock implementation where unlock is simply assigning zero to a volatile integer variable. The compiler was reordering unlock operation before the actual operation under the lock, unsurprisingly, leading to mysterious crashes.

    See:

    1. Lock-Free Code: A False Sense of Security
    2. Threads Cannot be Implemented as a Library

提交回复
热议问题