python 线程池(并行编程 22)

2019-07-30 10:31:11 浏览数 (3)

import threadpool

调用sum函数求和

def sum(start, end): sum = 0 for i in range(start, end 1): sum = i return sum

定义结果统一回调

totalsum = 0

def onresult(req, sum): global totalsum totalsum = sum

并发10条线程并求和

def threadpoolSum(): # 创建需求列表 reqlist = [] for i in range(10): reqlist.append(([i * 10 ** 7 1, 10 ** 7 * (i 1)], None)) reqs = threadpool.makeRequests(sum, reqlist, callback=onresult) # 创建线程为10的线程池 mypool = threadpool.ThreadPool(10) for item in reqs: mypool.putRequest(item)

代码语言:javascript复制
# 阻塞等待
mypool.wait()
# 打印结果
print(totalsum)

程序主入口

if name == 'main': threadpoolSum()

-----------------------------------------------进程池 import multiprocessing

调用sum函数求和

def sum(start, end): sum = 0 for i in range(start, end 1): sum = i return sum

结果统一回调并处理

totalsum = 0 def onresult(sum): global totalsum totalsum = sum

def MultiprocessPoolSum(): # 创建10条进程池 mypool = multiprocessing.Pool(10)

代码语言:javascript复制
for i in range(10):
    mypool.apply_async(sum, (i * 10 ** 7   1, 10 ** 7 * (i   1)), callback=onresult)
mypool.close()
mypool.join()
print(totalsum)

程序主入口

if name == 'main': MultiprocessPoolSum()

0 人点赞