Q1. What is test-and set instruction? How can it be used to implement mutual exclusion? Consider using a fragment of pseudo-assembly language, and add your explanation?
Ans. Some computers, especially those designed with multiple processors in mind, have an instruction like
TSL REGISTER LOCK
(Test and Set Lock). It reads the contents of the memory word lock into register RX and then stores a nonzero value at the memory address lock. The operations of reading the word and storing into it are guaranteed to be indivisible – no other processor can access the memory word until the instruction is finished. The CPU executing the TSL instruction locks the memory bus to prohibit other CPU’s from accessing memory until it is done.
To use the TSL instruction, we will use a shared variable, lock, to coordinate access to shared memory. When lock is 0, any process may set it to 1 using the TSL instruction and then read or write the shared memory. When it is done, the process sets lock back to 0 using an ordinary move instruction.
To prevent two processes from simultaneously entering there critical region, there are four instruction sub routines.
TSL REGISTER LOCK /*copy lock to register and set lock to 1 */
CMP REGISTER, #0 /*was lock zero?*/
JNE enter_region /*if it was nonzero, lock was set, so loop*/
RET /*return to caller, critical region entered*/
MOVE LOCK,#0 /*store a 0 in lock*/
RET /*return to caller*/
Before entering its critical region, a process calls enter_region, which does busy waiting until the lock is free; then it acquires the lock and returns. After the critical region the process calls leave_region, which stores a 0 in lock. As with all solutions based on critical regions, the processes must call enter_region and leave_region at the correct times for the method to work. If a process cheats, the mutual exclusion will fail.