自己写的线程池

#!/usr/bin/python
#coding=utf-8
#http://docs.python.org/library/threading.html
import threading, time, random

from collections import deque
class threadPool(object):
    def __init__(self, maxNum = 10):
        self.maxNum = maxNum
        self.deque = deque()

    def push(self, target, args = None):
        t = threading.Thread(target=target, args=args)
        self.deque.append(t)

    def run(self):
        while True:
            #队列没有进程就退出
            if len(self.deque) == 0: break
            if threading.activeCount() < self.maxNum + 1:
                t = self.deque.popleft()
                t.start()
            time.sleep(0.00001) #减少CPU的损耗

# Define a function for the thread
def print_time( threadName, delay):
    print "%s: %s\t%s" % ( threadName, time.ctime(time.time()) , delay)
    time.sleep(delay)
    

if __name__ == '__main__':
    pool = threadPool(2)
    for i in range(1000):
        pool.push(target=print_time, args=("Thread-%d" % i, random.randint(1, 100) * 0.001))
    pool.run()
原文地址:https://www.cnblogs.com/goodspeed/p/2647891.html