1
int64 g_some_global_variable = 1;

// thread 1
int64 a = g_some_global_variable;
// thread2
g_some_global_variable = 10;

thread 1 will generate asm code like this:

movl    a(%rip), %eax

I want to know, thread 1 should always get a 1 or a 10, there is never other possibilities? right?

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
ddwolf
  • 91
  • 2
  • 10
  • 3
    A `movl` to an aligned address is always atomic. Refer to the Intel SDM for details. – fuz Sep 28 '21 at 10:08
  • 4
    Note at the level of C, this is a data race, and therefore undefined behavior. If the compiler happens to emit a simple `movq` for the accesses to the global variable, it will turn out to be ok, but the compiler is not obligated to do so. The only way to make it safe is to use `_Atomic` types. – Nate Eldredge Sep 28 '21 at 13:46
  • 1
    `int64 g_some_global_variable` is a qword, but yes if you only want the low dword of it with a load into EAX, that's fine. Operand-sizes don't have to match for atomicity to be maintained. Of course as Nate says, and the canonical answer on [Why is integer assignment on a naturally aligned variable atomic on x86?](https://stackoverflow.com/q/36624881) explains, in C or C++ you need to be using `std::atomic` (optionally with `memory_order_relaxed`) if you're not writing by hand in asm. – Peter Cordes Sep 28 '21 at 15:24

0 Answers0