Muhammad Suleman
Muhammad Suleman

Reputation: 797

Python Queue.join()

Even if I do not set thread as Daemon, shouldn't the program exit itself once queue.join(), completes and unblocks?

#!/usr/bin/python
import Queue
import threading
import time

class workerthread(threading.Thread):
        def __init__(self,queue):
                threading.Thread.__init__(self)
                self.queue=queue
        def run(self):
                print 'In Worker Class'
                while True:
                        counter=self.queue.get()
                        print 'Going to Sleep'
                        time.sleep(counter)
                        print ' I am up!'
                        self.queue.task_done()
queue=Queue.Queue()

for i in range(10):
        worker=workerthread(queue)
        print 'Going to Thread!'
        worker.daemon=True
        worker.start()
for j in range(10):
        queue.put(j)
queue.join()

Upvotes: 7

Views: 28620

Answers (2)

GGG
GGG

Reputation: 271

I encountered the situation too, everything in the queue had been processed, but the main thread blocked at the point of Queue.task_done(), here is code block.

import queue
def test04():
    q = queue.Queue(10)
    for x in range(10):
        q.put(x)

    while q.not_empty:
        print('content--->',q.get())
        sleep(1)
    re = q.task_done()  
    print('state--->',re,'\n')
    q.join()
    print('over \n')

test04()

Upvotes: 1

NPE
NPE

Reputation: 500167

When you call queue.join() in the main thread, all it does is block the main threads until the workers have processed everything that's in the queue. It does not stop the worker threads, which continue executing their infinite loops.

If the worker threads are non-deamon, their continuing execution prevents the program from stopping irrespective of whether the main thread has finished.

Upvotes: 21

Related Questions