How does sig_atomic_t actually work?

前端 未结 5 2073
梦谈多话
梦谈多话 2020-11-30 02:19

How does the compiler or OS distinguish between sig_atomic_t type and a normal int type variable, and ensures that the operation will be atomic? Programs using both have sam

5条回答
  •  时光取名叫无心
    2020-11-30 03:19

    Note that sig_atomic_t is not thread-safe, only async-signal safe.

    Atomics involve two types of barriers:

    1. Compiler barrier. It makes sure that the compiler does not reorder reads/writes from/to an atomic variable relative to reads and writes to other variables. This is what volatile keyword does.
    2. CPU barrier and visibility. It makes sure that the CPU does not reorder reads and writes. On x86 all loads and stores to aligned 1,2,4,8-byte storage are atomic. Visibility makes sure that stores become visible to other threads. Again, on Intel CPUs, stores are visible immediately to other threads due to cache coherence and memory coherence protocol MESI. But that may change in the future. See §8.1 LOCKED ATOMIC OPERATIONS in Intel® 64 and IA-32 Architectures Software Developer’s Manual Volume 3A for more details.

    For comprehensive treatment of the subject watch atomic Weapons: The C++ Memory Model and Modern Hardware.

提交回复
热议问题