Warm tip: This article is reproduced from stackoverflow.com, please click
c++ embedded cpu atomic microprocessors

Do microprocessors disable interrupts while compare and swap instructions are executed?

发布于 2020-04-10 16:15:07

Does the 1.4 GHz Intel Core i5 (64 bit) CPU disable interrupts, when compare and swap instruction is executing?

In other words if I have std::atomic<int> atom_int;, does that mean during atom_int++; the signals (SIGINT, SIGSTP, SIGKILL) cannot be delivered to the process?

I understand its CPU specific question and was hoping to get answer for any specific CPU.

Questioner
PnotNP
Viewed
49
Andreas Wenzel 2020-02-03 00:49

The following two things are not necessarily the same:

  1. Atomic operations on a C++ level (std::atomic)
  2. Assembler CPU instructions that are guaranteed to be atomic

For example, a modern Intel processor guarantees that 64-bit reads/writes to a 64-bit aligned address is atomic. It also guarantees that an instruction with a LOCK prefix is executed atomically.

In C++, on the other hand, std::atomic guarantees that an operation on an object is executed atomically. A good compiler will use a single atomic CPU instructions for this, if possible. However, for larger objects, this atomicity cannot be accomplished with a single atomic CPU instruction. Therefore, atomicity can only be guaranteed by using more complex synchronization methods, such as locks. Such complex synchronization methods require several CPU instructions and can therefore always be interrupted.

You can determine whether std:atomic is using locks or not by calling std::atomic::is_lock_free().