#!/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()
自己写的线程池
最新推荐文章于 2024-09-04 20:18:34 发布