Skip to content

Instantly share code, notes, and snippets.

@jamesdavidson
Last active March 28, 2020 09:11
Show Gist options
  • Save jamesdavidson/2792cf627995e03c76a77e007a20cfdc to your computer and use it in GitHub Desktop.
Save jamesdavidson/2792cf627995e03c76a77e007a20cfdc to your computer and use it in GitHub Desktop.
Demo of basic producer/consumer just for fun.
# In this program there is a queue implemented as a list protected by a
# mutex so that the producer can run on one thread and the consumer can
# run on another thread. The dequeue_all method will return an empty list
# if there is no work (it does not block its caller).
from random import random
from random import shuffle
from time import sleep
from threading import Lock
from _thread import start_new_thread
from sys import version_info
# sanity check Python version
assert(version_info >= (3,7))
lock = Lock()
queue = []
def enqueue(x):
lock.acquire()
queue.append(x)
lock.release()
def dequeue_all():
lock.acquire()
xs = queue.copy() # duplicate queue value because we want to return the value after clearing the queue in the next line
queue.clear()
lock.release()
return xs
def produce():
while True:
sleep(random());
colours = ["red","orange","yellow","green","blue","indigo","violet"]
shuffle(colours) # eek! updates in-place
x = colours[0]
print("about to add "+str(x)+" to the queue")
enqueue(x)
# run producer as a background thread
start_new_thread(produce, ())
# give producer a five second head start
sleep(5)
# consume from the queue on the main thread
while True:
xs = dequeue_all()
print("got "+str(xs)+" off the queue")
sleep(0.1 * random()) # delay a little bit to reduce lock contention
# run for five more seconds
sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment