python线程池模块_python 多线程模块threadpool简单使用

python实现线程池通常使用threading或thread模块来编写,现在已经有了threadpool模块来实现线程池。

英文文档见:http://www.chrisarndt.de/projects/threadpool/

中文文档见:http://gashero.yeax.com/?p=44

现给出一个简易的使用threadpool模块来实现线程池的例子:

# -*-coding:utf-8-*-

__author__ = 'magicpwn'

import threadpool

import time, random

# worker 工作函数【多线程中每个线程工作的函数】

def worker_get(str):

return str

# 回调函数,接受的参数(请求本身,和请求工作函数执行结果)可以省略

def print_result(request, result):

print "the result is %s %r" % (request.requestID, result)

# data 设置为有20个随机1-10间的整数的列表,(列表中每一个数作为参数传递给工作函数运行一次)

data = [random.randint(1,10) for i in range(20)]

# 声明可容纳五个线程的池

pool = threadpool.ThreadPool(5)

# 创建线程运行内容请求列表(线程工作函数,线程工作参数列表,回调函数)

requests = threadpool.makeRequests(worker_get, data, print_result)

# 将每一个线程请求扔进线程池

[pool.putRequest(req) for req in requests]

# 等待data被消耗完,所有线程运行结束。

pool.wait()

上面的程序用pool.size个线程运行worker_get函数,处理了data.size个数据处理请求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值