consumer 1 got => [producer id=2, count=1]
consumer 1 got => [producer id=1, count=3]
consumer 1 got => [producer id=3, count=1]
consumer 0 got => [producer id=2, count=2]
consumer 1 got => [producer id=2, count=3]
consumer 1 got => [producer id=3, count=2]
consumer 1 got => [producer id=3, count=3]
Main thread exit.
Try adjusting the parameters at the top of this script to experiment with different sce-
narios. A single consumer, for instance, would simulate a GUI’s main thread. Here is
the output of a single-consumer run—producers still add to the queue in fairly random
fashion, because threads run in parallel with each other and with the consumer:
C:\...\PP4E\System\Threads> queuetest.py
consumer 0 got => [producer id=0, count=0]
consumer 0 got => [producer id=0, count=1]
consumer 0 got => [producer id=0, count=2]
consumer 0 got => [producer id=0, count=3]
consumer 0 got => [producer id=1, count=0]
consumer 0 got => [producer id=2, count=0]
consumer 0 got => [producer id=1, count=1]
consumer 0 got => [producer id=3, count=0]
consumer 0 got => [producer id=1, count=2]
consumer 0 got => [producer id=2, count=1]
consumer 0 got => [producer id=1, count=3]
consumer 0 got => [producer id=3, count=1]
consumer 0 got => [producer id=2, count=2]
consumer 0 got => [producer id=2, count=3]
consumer 0 got => [producer id=3, count=2]
consumer 0 got => [producer id=3, count=3]
Main thread exit.
In addition to the basics used in our script, queues may be fixed or infinite in size, and
get and put calls may or may not block; see the Python library manual for more details
on queue interface options. Since we just simulated a typical GUI structure, though,
let’s explore the notion a bit further.
Preview: GUIs and Threads
We will return to threads and queues and see additional thread and queue examples
when we study GUIs later in this book. The PyMailGUI example in Chapter 14, for
instance, will make extensive use of thread and queue tools introduced here and de-
veloped further in Chapter 10, and Chapter 9 will discuss threading in the context of
the tkinter GUI toolkit once we’ve had a chance to study it. Although we can’t get into
code at this point, threads are usually an integral part of most nontrivial GUIs. In fact,
the activity model of many GUIs is a combination of threads, a queue, and a timer-
based loop.
Here’s why. In the context of a GUI, any operation that can block or take a long time
to complete must be spawned off to run in parallel so that the GUI (the main thread)
208 | Chapter 5: Parallel System Tools
Do
wnload from Wow! eBook <www.wowebook.com>