[Python-checkins] cpython: Issue #12155: Fix queue doc example to join threads

victor.stinner python-checkins at python.org
Wed Mar 18 14:06:20 CET 2015


https://hg.python.org/cpython/rev/b44ec269abda
changeset:   95037:b44ec269abda
user:        Victor Stinner <victor.stinner at gmail.com>
date:        Wed Mar 18 14:05:43 2015 +0100
summary:
  Issue #12155: Fix queue doc example to join threads

Use None as a sentinel to stop a worker.

files:
  Doc/library/queue.rst |  34 ++++++++++++++++++++----------
  1 files changed, 22 insertions(+), 12 deletions(-)


diff --git a/Doc/library/queue.rst b/Doc/library/queue.rst
--- a/Doc/library/queue.rst
+++ b/Doc/library/queue.rst
@@ -158,22 +158,32 @@
 
 Example of how to wait for enqueued tasks to be completed::
 
-   def worker():
-       while True:
-           item = q.get()
-           do_work(item)
-           q.task_done()
+    def worker():
+        while True:
+            item = q.get()
+            if item is None:
+                break
+            do_work(item)
+            q.task_done()
 
-   q = Queue()
-   for i in range(num_worker_threads):
-        t = Thread(target=worker)
-        t.daemon = True
+    q = queue.Queue()
+    threads = []
+    for i in range(num_worker_threads):
+        t = threading.Thread(target=worker)
         t.start()
+        threads.append(t)
 
-   for item in source():
-       q.put(item)
+    for item in source():
+        q.put(item)
 
-   q.join()       # block until all tasks are done
+    # block until all tasks are done
+    q.join()
+
+    # stop workers
+    for i in range(num_worker_threads):
+        q.put(None)
+    for t in threads:
+        t.join()
 
 
 .. seealso::

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list