Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 680
Muhammad Suleman Avatar asked Nov 29 '14 09:11

Muhammad Suleman


1 Answers

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.

like image 169
NPE Avatar answered Oct 07 '22 09:10

NPE