Python Queue.join ()

Even if I don't set up the thread as a Daemon, shouldn't the program exit by itself after queue.join () exits and unlocks?

#!/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()

      

Any help would be much appreciated!

+3


source to share


2 answers


When you call queue.join()

on the main thread, all it does is block the main threads until the workers have processed everything in the queue. It does not stop worker threads that continue to execute their infinite loops.



If the worker threads are non-deamon, their continued execution prevents the program from stopping regardless of the main thread terminating.

+11


source


I also ran into the situation, everything in the queue was processed, but the main thread is blocked at the Queue.task_done () point, here is the 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()

      

0


source







All Articles