Python多线程

from Queue import Queue
from threading import Thread
import threading
import time

ERROR_LIST = []

class Consumer(Thread):

    def __init__(self, tasks):
        Thread.__init__(self)
        self.tasks = tasks
        self.daemon = True
        self.start()
        
    def run(self):
        """This is the Consumer thread function.
    It processes items in the queue one after
    another.  These daemon threads go into an
    infinite loop, and only exit when
    the main thread ends.
    """
        while True:
            func, args, kargs = self.tasks.get()
            try:
                func(*args, **kargs)
            except Exception, e:
                print e
                #raise Exception
                ERROR.append(e)
            finally:
                pass
            self.tasks.task_done()
            
class ThreadPool:

    def __init__(self, num_threads):
        self.tasks = Queue(num_threads)
        for _ in range(num_threads):
            Consumer(self.tasks)

    def add_task(self, func, *args, **kargs):
        """Put item into the queue. If optional 
    args block is true and timeout is None 
    (the default), block if necessary until 
    a free slot is available
    """
        self.tasks.put((func, args, kargs))

    def wait_completion(self):
        self.tasks.join()



class Test():
    def __init__(self, str):
        self.str = str
        pass

    def test(self, dumy):
        print self.str
        time.sleep(1)
        pass

astr_list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
        
pool = ThreadPool(3)
for str in astr_list:
   pool.add_task(Test(str).test, (None))
pool.wait_completion()
if ERROR:
   raise Exception, Error

Python中Queue相关的注解:

Queue.put(item[, block[, timeout]]) 
    Put item into the queue. If optional args block is true and timeout is None (the default), block if necessary until a free slot is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Full exception if no free slot was available within that time. Otherwise (block is false), put an item on the queue if a free slot is immediately available, else raise the Full exception (timeout is ignored in that case).

Queue.get([block[, timeout]]) 
    Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

Queue.task_done() 
    Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete.

    If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue).

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 that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.
原文地址:https://www.cnblogs.com/Ice-Max/p/4421738.html