Should I protect operations on primitive types with mutexes for being thread-safe in C++?

后端 未结 4 1757
清酒与你
清酒与你 2021-01-20 15:20

What is the best approach to achieve thread-safety for rather simple operations?

Consider a pair of functions:

void setVal(int val)
{
    this->_         


        
4条回答
  •  面向向阳花
    2021-01-20 15:56

    On 32-bit x86 platforms, reads and writes of 32-bit values aligned on 4-byte boundary are atomic. On 64-bit platforms you can also rely on 64-bit loads and stores of 8-byte aligned values to be atomic as well. SPARC and POWER CPUs also work like that.

    C++ doesn't make any guarantees like that, but in practice no compiler is going to mess with it, since every non-trivial multi-threaded program relies on this behaviour.

提交回复
热议问题