Python--线程池

# 放线程的一个池子
import threadpool

def say(num):
print(num)
res = list(range(101))

pool = threadpool.ThreadPool(10)  # 创建一个线程池
reqs = threadpool.makeRequests(say, res)  # 生成线程要执行的所有线程
# for req in reqs:
# pool.putRequest(req) # 实际才去执行的
[pool.putRequest(req) for req in reqs]
pool.wait() # 等待 其他线程执行结束


封装线程池
import threadpool


class MyPool(object):
def __init__(self, func, size=20, data=None):
self.func = func
self.size = size
self.data = data
self.pool() # 实例化之后就可以了

def pool(self):
pool = threadpool.ThreadPool(self.size) # 创建一个线程池,指定大小
reqs = threadpool.makeRequests(self.func, self.data) # 生成请求,分配数据
[pool.putRequest(req) for req in reqs] # 执行函数
pool.wait() # 等待线程执行完成


def down(num):
print(num)


my = MyPool(func=down, data=[1, 2, 3, 4, 5, 6, 7, 8, 9])
posted @ 2018-03-15 10:16  王思磊  阅读(784)  评论(0编辑  收藏  举报