How could we implement locks? No matter how we choose to implement them, we must have some hardware support. One possibility for implementing locks on a uniprocessor machine is is to disable interrupts when testing/setting locks. With interrupts disabled on a single processor machine, the processor cannot switch processes, and so we can guarantee that only the active process will have access to the shared data. Another option would be to make use of atomic operations, such as test and set. This type of operation (which usually corresponds to a single atomic assembly instruction) behaves as if it used the following C function, atomically:
int test_and_set(int x) // let x be strictly either 0 or 1.
{
if (x) { return 1; } else { x=1; return 0; }
}
All this needs to be implemented atomically, in hardware. Using this type of atomic operation, one could implement thread lock(l) simply as while test_and_set(l) {
; // do nothing
} // spinlock version of thread_lock()
and thread unlock(l) simply as
l = 0; // we need this to be an atomic clear (or assign) instruction
The assembly instruction test and set can bemade to be atomic acrossmultiple processors. An equivalent option would be an atomic compare and swap assembly instruction. These low-level hardware solutions are then built up into high-level functions, either built into the languages, or in libraries. In general, do not implement your own locking functions, but rather use functions from a tested library. Getting things right can be tricky, and your own solution is also likely to be non-portable.