Synchronization in Python
Prev: Not remotely classical problems Next: Synchronization in C
Mutex checker problem
The unsynchronized program is:
class Shared:
def __init__(self, end=10):
self.counter = 0
self.end = end
self.array = [0] * self.end
def child_code(shared):
while True:
if shared.counter >= shared.end:
break
shared.array[shared.counter] += 1
shared.counter += 1If everything works correctly, each entry in array should be incremented exactly once.
Exercise
Add synchronization code to this program to enforce exclusive access to the shared variables.
The coke machine problem
The program simulates producers and consumers adding and removing cokes from a machine:
import random
class Shared:
def __init__(self, start=5):
self.cokes = start
def consume(shared):
shared.cokes -= 1
print(shared.cokes)
def produce(shared):
shared.cokes += 1
print(shared.cokes)
def loop(shared, f, mu=1):
while True:
t = random.expovariate(1.0 / mu)
time.sleep(t)
f(shared)The machine capacity is 10 cokes, and it starts half full.
Exercise
Add code to this program to enforce the following synchronization constraints:
- Access to
cokesshould be mutually exclusive. - If the number of cokes is zero, consumers should block until a coke is added.
- If the number of cokes is 10, producers should block until a coke is removed.