The Little Book of Semaphores
basic synchronization patterns
signaling
Signaling: One thread sends a signal to another thread to indicate something has happened (ie - completed some work, start another work
print("statmenet a1 complete")
sem.signal()
sem.wait()
print("got the signal!")
rendezvous
Rendezvous: threads should not start the critical path until meeting at the "rendezvous" point
print("rendezvous")
sem1.signal() # signal to the other thread that Im ready
sem2.wait() # wait for other thread to signal me
print("critial point")
#####################
print("rendezvous")
sem2.signal()
sem1().wait()
print("critical point")
mutex
Mutex: Means Mutual Exclusion, guarantees that only one thread accesses a shared variable at a time.
mutex = Semaphore(1) # Initialize the semaphore to 1, so that the first wait decrements it to 0 but does not block. (wait only blocks if the value is not positive)
#############################
mutex.wait() # now the semaphore value is 0, so that means the next person arriving at this mutex will wait
count += 1 # modify the shared variable
mutex.signal() # release the hold on the mutex
multiplex
multiplex: General version of a mutex, but allow n threads to access the critical section at the same time
multiplex = Semaphore(n) # Initialize the semaphore to n
##############################
mutex.wait()
print("critical section")
mutex.signal()
barrier
barrier: generalization of the rendezvous pattern. n threads should complete the rendezvous before proceeding to the critical point
# barrier = Semaphore(0)
# mutex = Semaphore(1)
# count = 0
print("rendezvous")
mutex.wait()
count += 1
if count == n: barrer.signal()
mutex.signal()
barrier.wait()
barrier.signal()
# the barrier.wait() / barrier.signal() pattern is called a turnstile
print("critical point")
reusable barrier
reusable barrier: the barrier locks/ resets after all threads have passed through, so that it can be used again
non solution
# barrier = Semaphore(0)
# mutex = Semaphore(1)
# count = 0
print("rendezvous")
mutex.wait()
count += 1
if count == n: barrier.signal()
mutex.signal()
barrier.wait()
barrier.signal()
print("critical point")
mutex.wait()
count -= 1
if count == 0: barrier.wait()
mutex.signal()