Is this a proper implementation of semaphores:
Code: Select all
struc SEMAPHORE
thread_list LIST
int VAL = 1
end
to GET_A_SEM
DEC_ATOMIC ( SEMAPHORE.VAL )
if SEMAPHORE.VAL is above-or-equal TO zero RETURN;
ADD-TO-THREAD-LIST ( this-thread)
SLEEP(0)
RETURN
end
to RELEASE_A_SEM
if SEMAPHORE.VAL less THAN zero { AWAKE-FIRST-THREAD ( from LIST)
INC_ATOMIC ( SEMAPHORE.VAL )
RETURN
end
val= 1 (semaphore-creation:)
thread-1: (val == 1) acquire sem; (val==0)
thread-2: (val==0) acquire sem; (val==-1) sleep
thread-1: (val==-1) release sem; awake thread2; val++; (val==0)
thread-2: (val==0) release sem; (val==1)
Cheers,
Adrian