Quiz 3
Explore different synchronization techniques in Python multiprocessing to solve the ping-pong problem. Understand why initializing semaphores matters and why a single semaphore can fail. Learn how condition variables and locks can be used to coordinate process communication and enforce correct printing order.
We'll cover the following...
We'll cover the following...
Question # 1
Consider the ping pong program from the Semaphore section. Will the program work if both the semaphores sem1 and sem2 are initialized to 1 instead of 0? The code is reproduced below for reference:
from multiprocessing import Semaphore, Process, Value
from ctypes import c_bool
import time
import multiprocessing
def process_A(sem1, sem2, exit):
while not exit.value:
print("ping")
sem1.release()
sem2.acquire()
time.sleep(0.05)
def process_B(sem1, sem2, exit):
while not exit.value:
# wait for a prime number to become available
sem1.acquire()
print("pong")
sem2.release()
time.sleep(0.05)
if __name__ == '__main__':
sem1 = Semaphore(0) # change from 0 to 1 for this question
sem2 = Semaphore(0) # change from 0 to 1 for this question
exit_prog = Value(c_bool, False)
processA = Process(target=process_A, args=(sem1, sem2, exit_prog))
processA.start()
processB = Process(target=process_B, args=(sem1, sem2, exit_prog))
processB.start()
# Let the threads run for 3 seconds
time.sleep(3)
exit_prog.value = True
processA.join()
processB.join()
Given the current structure of the code, the program may not produce the ...