user4092851
user4092851

Reputation:

Thread not exiting

I am learning about Thread in Python and am trying to make a simple program, one that uses threads to grab a number off the Queue and print it.

I have the following code

import threading
from Queue import Queue

test_lock = threading.Lock()

tests = Queue()

def start_thread():
    while not tests.empty():
        with test_lock:
            if tests.empty():
                return
            test = tests.get()
        print("{}".format(test))

for i in range(10):
    tests.put(i)
threads = []
for i in range(5):
    threads.append(threading.Thread(target=start_thread))
    threads[i].daemon = True
for thread in threads:
    thread.start()
tests.join()

When run it just prints the values and never exits.

How do I make the program exit when the Queue is empty?

Upvotes: 0

Views: 57

Answers (1)

Alex Hall
Alex Hall

Reputation: 36013

From the docstring of Queue.join():

Blocks until all items in the Queue have been gotten and processed.

The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete.

When the count of unfinished tasks drops to zero, join() unblocks.

So you must call tests.task_done() after processing the item.

Since your threads are daemon threads, and the queue will handle concurrent access correctly, you don't need to check if the queue is empty or use a lock. You can just do:

def start_thread():
    while True:
        test = tests.get()
        print("{}".format(test))
        tests.task_done()

Upvotes: 1

Related Questions