Lesson 1 · Unit 03
Producer and consumer
Hand work between threads through a queue
What you practise
- A thread-safe queue hands work between threads, bounded queues and backpressure, sentinel values to shut down, share by communicating
Try a question from this lesson
Pick one
Two worker threads run this loop on one shared list of jobs. Which bug is waiting to happen?
def worker():
while True:
if jobs: # check
job = jobs.pop(0) # act
handle(job)Hint
Two threads can both pass the check before either one pops.
Correct answer
Both see one job left, then both pop: one hits an empty list
Why
It is check-then-act again: the list can empty between the if and the pop. And while the list is empty, both loops spin at full speed doing nothing. A thread-safe queue fixes both problems.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A queue between threads
queue.Queue is a thread-safe pipe. put adds an item at the back. get takes one from the front, and waits if the queue is empty.
The locking is inside the queue, so your code needs none.
One thread produces, another consumes. They no longer share data: they hand it over.
import queue
q = queue.Queue()
q.put("job 1")
q.put("job 2")
print(q.get()) # first in, first outConcept
Saying "no more work"
A consumer in a while True loop cannot tell an empty queue from a finished job.
The producer tells it with a sentinel: a special value, often None, that means "nothing more is coming". The consumer leaves its loop when it takes one.
The sentinel travels through the queue like any item, so it arrives after all the real work.
10 more exercises in the app
- 5× type the answer
- 2× true or false
- 1× fill the blanks
- 2× multiple choice
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.