Implementing a Binary Semaphore

Assume that the Test and Set operation, applied to a byte B byte in main memory, sets B to zero and sets the processor status flag Z to indicate whether B was zero initially. Then we can build a simple binary semaphore, with busy waiting, as follows:

ASSEMBLER CODES:

	DS	Define storage
	TS	Test and Set
	BZ	Branch if Zero
	SI	Store Immediate

INITIALIZATION:
	DS	SEM1,BYTE	/ SEM1 is a byte
	SI	SEM1,1		/ initial value is 1
				/ 0 means BUSY, 1 means FREE
P(SEM1):
L1:	TS	SEM1		/ set SEM1 to BUSY, capture previous value in Z
	BZ	L1		/ if it was BUSY, loop
				/ if not, enter critical section
				/ SEM1 is set to BUSY now.
V(SEM1):
	SI	SEM1,1		/ reset SEM1 to FREE