It is said an assembly instruction prefixed by “lock” is atomic. I want to know if “lock” can only affect one assembly instruction; Is an assembly instruction itself not atomic?
Here is an example of an atomic function in linux kernel:
static __inline__ int atomic_sub_and_test(int i, atomic_t *v)
{ unsigned char c;
__asm__ __volatile__(
LOCK "subl %2,%0; sete %1"
:"=m" (v->counter), "=qm" (c)
:"ir" (i), "m" (v->counter) : "memory");
return c; }
In this example can subl and sete be interrupted?
The lock prefix affects a single instruction.
Instructions stop being atomic when they modify memory shared between several CPUs. Modifications that involve reading a memory operand, performing some operation on it (e.g. AND, XOR, INC, etc) and then writing it back are not seen as atomic by other CPUs. The lock prefix “locks” the memory location, so the 3 steps (Read, Modify, Write) look as one, i.e. other CPUs can only observe what was before and what was after the locked instruction.
See the official CPU documentation from Intel or AMD.
EDIT: In your newly added example neither of those instructions can be interrupted, if we’re talking about interrupts. Interrupts occur between entire instructions. The lock prefix makes the
subinstruction atomic. Theseteinstruction is not intended to be atomic, it’s there to transform theZFflag into a zero or non-zero integer value.