zoukankan      html  css  js  c++  java
  • 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.
  • 相关阅读:
    Spring事务深入剖析--spring事务失效的原因
    CentOS 安装 VMware Tools 详细方法
    -手写Spring注解版本&事务传播行为
    手写spring事务框架-蚂蚁课堂
    springMvc接口开发--对访问的restful api接口进行拦截实现功能扩展
    spring框架中JDK和CGLIB动态代理区别
    mysql事务的坑----MyISAM表类型不支持事务操作
    git 远程分支和tag标签的操作
    git fetch和git pull的区别
    umask 文件默认权限
  • 原文地址:https://www.cnblogs.com/Ice-Max/p/4421738.html
Copyright © 2011-2022 走看看