However, this approach is quite useful for coordinating threads in an operating system on
a multiprocessor machine. The effect of the busy wait is much less onerous when the waiting thread has its own
processor, and the wait is not likely to be long.
There are other variations on the test-and-set instruction idea. A ???swap??™ or ???exchange??™ instruction that
atomically (without interruption) exchanges the values of two arguments can be used the same way. Here is
pseudocode for a swap instruction:
void swap(boolean a, boolean b) {
boolean temp = a;
a = b;
b = temp;
}
This code says:
Given two boolean values (a and b can each be either true or false),
exchange the two values, using the variable temp for temporary storage.???
(The void means that this routine does not return any value. It simply swaps a and b.)
Application code such as the following uses the swap instruction:
CHAP. 6] OPERATING SYSTEMS 105
boolean lock; // shared data; initialized to 'false'
boolean key = true; // not shared; used for this thread only
. . .
//Wait until key becomes false, which means lock was false
while ( key ) swap(lock, key);
/* critical section */
...
/ ??— Now free the lock ??—/
lock = false;
..
Pages:
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289