zoukankan      html  css  js  c++  java
  • python 多线程

    #coding:gbk

    import Queue

    import threading

    import sys

    class WorkerManager:   

       def __init__(self, num_of_workers=10, timeout = 1):   

           self.workQueue = Queue.Queue()   

           self.resultQueue = Queue.Queue()   

           self.threads = []   

           self.timeout = timeout   

           self._recruitThreads(num_of_workers)

           

       def _recruitThreads(self, num_of_workers):   

           for i in range(num_of_workers):   

               thread = Worker(self.workQueue, self.resultQueue, self.timeout)   

               self.threads.append(thread)

               

       def wait_for_complete(self):   

           while len(self.threads):   

               thread = self.threads.pop()   

               thread.join( )   

               if thread.isAlive() and not self.workQueue.empty():   

                   self.threads.append(thread)   

           

       def add_job(self, callable, *args, **kwds ):   

           self.workQueue.put((callable, args, kwds))

           

       def get_result(self, *args, **kwds):   

           return self.resultQueue.get(*args, **kwds)

        

    class Worker(threading.Thread):

       def __init__( self, workQueue, resultQueue, timeout = 0, **kwds):   

           threading.Thread.__init__( self, **kwds )   

           self.setDaemon(True)   

           self.workQueue = workQueue   

           self.resultQueue = resultQueue   

           self.timeout = timeout   

           self.start()

           

       def run( self ):   

           while True:   

               try:   

                   callable, args, kwds = self.workQueue.get(timeout=self.timeout)   

                   res = callable(*args, **kwds)   

                   self.resultQueue.put(res)   

               except Queue.Empty:   

                   break   

               except:

                   print 'Worker: %s %s %s' % sys.exc_info()

    def func(index, fname):

        print index, fname

        

    if __name__=='__main__':

        flist = [1,2,3,4,5,6,7,8,9,10]

        worker_num = 2

        wm = WorkerManager(worker_num)

        for i in range(len(flist)):

            fname = flist[i]

            wm.add_job(func, i, fname)

            

        wm.wait_for_complete()

  • 相关阅读:
    为Jboss4配置数据库
    从JAVA源代码到EXE可执行文件
    连接数据库出现:Connections could not be acquired from the underlying database
    SVN修改用户名与密码
    linux 下开放指定端口
    Nginx 禁止IP访问及未绑定的域名跳转
    Proguard混淆后无法正常运行的问题:
    How To Automate Internet Explorer to POST Form Data
    poj 2667 hotel 线段树
    poj 3691 DNA repair AC自动机+DP
  • 原文地址:https://www.cnblogs.com/NancyStartOnce/p/6826215.html
Copyright © 2011-2022 走看看