import threadpool
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
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)
# 阻塞等待
mypool.wait()
# 打印结果
print(totalsum)
if name == 'main': threadpoolSum()
-----------------------------------------------进程池 import multiprocessing
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)
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()