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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值