import sys from threading import * from time import sleep from random import random from math import log running = True mutex = Semaphore(1) num_cokes = 5 def consume(): global num_cokes mutex.acquire() num_cokes -= 1 print num_cokes mutex.release() def produce(): global num_cokes mutex.acquire() num_cokes += 1 print num_cokes mutex.release() def rand_exponential(): while 1: x = random() if x > 0: break return -log(x) def loop(f): global running while running: f() t = rand_exponential() sleep(t) def entry(f): global running try: loop(f) except KeyboardInterrupt: running = False def run_in_thread(function, *args): thread = Thread(target=function, args=args) thread.start() return thread def main(script, *args): global running t1 = run_in_thread(entry, consume) t2 = run_in_thread(entry, produce) try: while running: sleep(1) except KeyboardInterrupt: running = False t1.join() t2.join() if __name__ == '__main__': main(*sys.argv)