operating-systems hardware concurrency
Definition
Exchange Instruction
The exchange instruction (or swap instruction) is an atomic hardware operation that interchanges the contents of a register and a memory location (or two registers) in a single, ununterruptable step.
Like Test-and-Set, this instruction is used to implement mutual exclusion by providing a reliable way to acquire a lock.
Mechanism
The logic of the exchange operation can be described as follows:
procedure exchange (var a, b: integer);
var temp: integer;
begin
temp := a;
a := b;
b := temp;
end;Implementation of Mutual Exclusion
Using the exchange instruction, a process can attempt to enter a critical section by “swapping” its local key with a global lock variable.
// global variable: var b: integer; (initialised to 0)
// Process Pi:
var key: integer := 1; // Local variable
repeat
exchange(key, b);
until (key = 0); // Busy Waiting until we get the '0' from the lock
// --- Critical Section ---
exchange(key, b); // Release lock by swapping back
// --- Remainder Section ---Comparison with Test-and-Set
While functionally similar, the exchange instruction is often more flexible in architectures where multiple registers are available. Both rely on busy waiting (spinning) if the lock is already held, making them less efficient for long-duration waits than kernel-level semaphores.