Ending a thread life in python?

I have the code below, but it lives after the queue is empty, any ideas:

def processor():
   while(1>0):
    if queue.empty() == True:  
    print "the Queue is empty!"  
    break
   source=queue.get()
   page = urllib2.urlopen(source)
   print page   

def main:
   for i in range(threads):  
    th = Thread(target=processor)  
    th.setDaemon(True)  
    th.start()  
   queue.join()  

It prints the queue empty as many times as I have threads, and just does nothing there.

+3
source share
3 answers

You need to call queue.task_done () after the page prints, otherwise join () will be blocked. Each thread after using get () should call task_done ().

See queue documentation

+4
source

This part:

   while(1>0):
    if queue.empty() == True:  
    print "the Queue is empty!"  
    break

Above all, just wrong . queue.get()is blocked, there is absolutely no reason for the busy cycle . It should be removed.

Your code should look something like this.

def processor():
   source=queue.get()
   page = urllib2.urlopen(source)
   print page   
   queue.task_done()

def main:
   for i in range(threads):  
    th = Thread(target=processor)  
    th.setDaemon(True)  
    th.start()  
   for source in all_sources:
    queue.put(source)
   queue.join()  

, . , , main.

+3

, , , :

Pythons Thread Javas Thread; , , , , , .

, run() - , . is_alive() , .

http://docs.python.org/library/threading.html

exit(). , , , Thread , run() .

http://docs.python.org/library/thread.html

+1

All Articles