以下是简单的4行代码:
pool = threadpool.ThreadPool(10) #建立线程池,控制线程数量为10
reqs = threadpool.makeRequests(get_title, data, print_result)
#构建请求,
#get_title为要运行的函数,data为要多线程执行函数的参数,
#最后这个print_result是可选的,是对前两个函数运行结果的操作
[pool.putRequest(req) for req in reqs] #多线程一块执行
pool.wait() #线程挂起,直到结束
创建线程池,线程数为10:
pool = threadpool.ThreadPool(10)
创建线程请求,包涵调用的函数、参数和回调函数:
requests = threadpool.makeRequests(func, args_list, call_back)
# 源代码
# `args_list`` should be either a 2-item tuple of the list of positional arguments and a dictionary of keyword arguments or a single, non-tuple argument.
args_list必须是包含2个元素的元组,第一个是list,第二个是dict,如果线程函数需要多个参数,需要拼接list或者dict。
# 方法1
lst_vars_1 = ['1', '2', '3']
lst_vars_2 = ['4', '5', '6']
func_var = [(lst_vars_1, None), (lst_vars_2, None)]
# 方法2
dict_vars_1 = {'m':'1', 'n':'2', 'o':'3'}
dict_vars_2 = {'m':'4', 'n':'5', 'o':'6'}
func_var = [(None, dict_vars_1), (None, dict_vars_2)]
将所有要运行多线程的请求扔进线程池:
[pool.putRequest(req) for req in requests]
# 等同于
for req in requests:
pool.putRequest(req)
等待所有的线程完成工作后退出:
pool.wait()
示例:
#!/usr/bin/env python
# coding:utf-8
import time
import random
import threadpool
HEHE = dict()
def sayhello(name, v):
global HEHE
if HEHE.has_key(name):
HEHE[name] = HEHE[name] + '+' + v
else:
HEHE[name] = v
#time.sleep(2)
#name_list = [(['caoshuai', '1'], None), (['yangliu', '2'], None),(['caoshuai', '3'], None),(['ss', '10'], None),(['wwwwww', '12'], None),]
name_list = [(['caoshuai','1'],None),(['caoshuai','2'],None),(['a','3'],None),(['ss','10'],None),(['wwwwww','12'],None),(['m','12'],None),(['n','12'],None),(['b','12'],None),(['v','12'],None),(['x','12'],None),(['z','12'],None),]
#name_list = [1, -5, 6, -4]
start_time = time.time()
pool_t = threadpool.ThreadPool(4)
requestss = threadpool.makeRequests(sayhello, name_list)
[pool_t.putRequest(req) for req in requestss]
pool_t.wait()
print HEHE
print "%s second" % (time.time()-start_time)
while True:
time.sleep(1)
结果收集用callback参数
callback必须接受2个匿名参数, 按顺序分别是WorkRequest对象和任务函数的结果。
举个栗子
def save_callback(request, result):
# 第1个参数是request,可以访问request.requestID
# 第2个参数是request执行完的结果
print(request.requestID, result)
with open('result.txt', 'a') as f:
f.write(result + '\n')
def get_user_info(uid, sex, name, age):
time.sleep(0.3)
return "{0},{1},{2},{3}".format(uid, sex, name, age)
if __name__ == '__main__':
num = 100
para_list = [[i, 'male'] for i in range(1, num)]
users = list()
for i in range(1, num):
user = {'name'.format(i): 'user{0}'.format(i),
'age': i}
users.append(user)
params = zip(para_list, users)
# print(params)
# 形如[([1, 'male'], {'age': 1, 'name': 'user1'}), ...]的参数列表
pool_size = 10
pool = threadpool.ThreadPool(pool_size)
requests = threadpool.makeRequests(get_user_info, params, save_callback)
for req in requests:
pool.putRequest(req)
pool.wait()
```