详解python中threadpool线程池任务终止示例代码

需求

加入我们需要处理一串个位数(0~9),奇数时需要循环打印它;偶数则等待对应时长并完成所有任务;0则是错误,但不需要终止任务,可以自定义一些处理。

关键点

定义func函数处理需求

callback处理返回结果,只有偶数和0返回;奇数会一直执行;要控制线程池状态,则需要针对偶数和0时抛出异常,并捕获异常处理。

threadpool定义线程池并发

实现# -*- coding: utf-8 -*-
from threadpool import makerequests, threadpool
import time
from multiprocessing import process异常定义和特殊值(0)定义class finish(syntaxwarning):
passclass pauseinfo(syntaxwarning):
pass
pause_num = 0func函数定义

0时返回false,其他偶数返回true

def func(para):
if para == pause_num:
print(‘start for %d and wait %ds’ % (para, 4))
time.sleep(4)
print(‘error bcs ‘,para)
return false
if para % 2 == 0:
print(‘start for %d and wait %ds’ % (para, para))
time.sleep(para)
print(‘stop for’, para)
return true
while true:
print(‘continue for’, para)
time.sleep(para)callback定义def callback(request, result):
if result:
raise finish
else:
raise pauseinfo线程池处理

finish标识任务完成,再次诱发异常退出线程池处理;

def main_thread(paras):
pool = threadpool(10)
requests = makerequests(callable_=func, args_list=paras, callback=callback)
[pool.putrequest(req) for req in requests]
while true:
try:
pool.wait()
except finish as e:
raise systemexit
except pauseinfo as e:
print(‘pause bcs %d but will continue’ % pause_num)
except exception as e:
print(‘unknown error so will quit’)
raise systemexit主函数起一个测试进程if name == ‘main’:
while true:
s = input(‘input number list to test and any other word to quit\n’)
paras = []
for para in s:
if para.isnumeric():
paras.append(int(para))
else:
break
try:
thread_test = process(target=main_thread, args=(paras,))
thread_test.start()
thread_test.join(timeout=20)
except timeouterror as e:
print(‘task timeout’)
except exception as e:
print(‘unknow error:’,e) 结果验证

处理108,看打印可以看到,1被循环处理,0处理的时候报错;8处理完毕则任务结束

input number list to test and any other word to quit108continue for 1start for 0 and wait 4sstart for 8 and wait 8scontinue for 1continue for 1continue for 1error bcs 0continue for 1pause bcs 0 but will continuecontinue for 1continue for 1continue for 1continue for 1stop for 8input number list to test and any other word to quit

以上就是详解python中threadpool线程池任务终止示例代码的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类

发表评论