Is it safe to read an integer variable that's being concurrently modified without locking?

前端 未结 12 1348
青春惊慌失措
青春惊慌失措 2020-12-02 09:03

Suppose that I have an integer variable in a class, and this variable may be concurrently modified by other threads. Writes are protected by a mutex. Do I need to protect re

12条回答
  •  失恋的感觉
    2020-12-02 09:32

    You ask a question about reading a variable and later you talk about updating a variable, which implies a read-modify-write operation.

    Assuming you really mean the former, the read is safe if it is an atomic operation. For almost all architectures this is true for integers.

    There are a few (and rare) exceptions:

    • The read is misaligned, for example accessing a 4-byte int at an odd address. Usually you need to force the compiler with special attributes to do some misalignment.
    • The size of an int is bigger than the natural size of instructions, for example using 16 bit ints on a 8 bit architecture.
    • Some architectures have an artificially limited bus width. I only know of very old and outdated ones, like a 386sx or a 68008.

提交回复
热议问题