简体   繁体   中英

Are C++ int operations atomic on the mips architecture

I wonder if I could read or write shared int value without locking on mips cpu (especially Amazon or Danube). What I mean is if such a read or write are atomic (other thread can't interrupt them). To be clear - I don't want to prevent the race between threads, but I care if int value itself is not corrupted.

Assuming that the compiler aligns all ints at the boundaries of cpu word, it should be possible. I use gcc (g++). Tests also shows that it seems work correctly. But maybe someone knows it for sure?

Use gcc's builtin atomic operations and you'll get warnings if they're not supported: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html

It looks like combinations of addition/subtraction and testing (at least) are possible on the hardware: http://rswiki.csie.org/lxr/http/source/include/asm-mips/atomic.h

Depends on the operation. Having stared at enough disassembled programs in MIPS, I know that only some operations are atomic.

assignment of a new value could be 1 op or more, you'd have to look at the assembly.

eg:

x = 0; // move $a0, $0


x = 0x50000; // lui $a0, 0x0005


x = 0x50234; // lui $a0, 0x0005
             // ori $a0, 0x0234

MIPS assembley reference or here

see here to see danube and amazon are MIPS32, which my example covers, and therefore not all 32bit integer immediate can be written atomically.

see R10000 in above posting is MIPS64. Since a 32bit value would be half the register size, it could be an atomic load/write.

Which operations? It's plausible that int a; a=42; int a; a=42; is atomic. There's no guarantee that a= a+42; is atomic, or in any variants like with ++ . Also, you have to be concerned about what the optimizer might do, say by holding an intermediate value in a register when convenient.

The question invites misleading answers.

You can only authoritatively answer "is it atomic" questions about assembly/machine language.

Any given C/C++ code fragment makes no guarantees, can vary depending on exactly which compiler (and version) you use, etc. (Unless you call some platform-specific intrinsic or whatnot that is guaranteed to compile to a known atomic machine instruction.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM