日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python停止线程池_详解python中Threadpool线程池任务终止示例代码

發(fā)布時間:2025/3/20 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python停止线程池_详解python中Threadpool线程池任务终止示例代码 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

需求

加入我們需要處理一串個位數(shù)(0~9),奇數(shù)時需要循環(huán)打印它;偶數(shù)則等待對應時長并完成所有任務;0則是錯誤,但不需要終止任務,可以自定義一些處理。

關鍵點

定義func函數(shù)處理需求

callback處理返回結(jié)果,只有偶數(shù)和0返回;奇數(shù)會一直執(zhí)行;要控制線程池狀態(tài),則需要針對偶數(shù)和0時拋出異常,并捕獲異常處理。

threadpool定義線程池并發(fā)

實現(xiàn)# -*- coding: utf-8 -*-

from threadpool import makeRequests, ThreadPool

import time

from multiprocessing import Process

異常定義和特殊值(0)定義class Finish(SyntaxWarning):

passclass PauseInfo(SyntaxWarning):

pass

pause_num = 0

func函數(shù)定義

0時返回False,其他偶數(shù)返回Truedef 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標識任務完成,再次誘發(fā)異常退出線程池處理;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

主函數(shù)起一個測試進程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)

結(jié)果驗證

處理108,看打印可以看到,1被循環(huán)處理,0處理的時候報錯;8處理完畢則任務結(jié)束

Input number list to test and any other word to quit

108

continue for 1

start for 0 and wait 4s

start for 8 and wait 8s

continue for 1

continue for 1

continue for 1

error bcs 0

continue for 1

Pause bcs 0 but will continue

continue for 1

continue for 1

continue for 1

continue for 1

stop for 8

Input number list to test and any other word to quit

以上就是詳解python中Threadpool線程池任務終止示例代碼的詳細內(nèi)容,更多請關注php中文網(wǎng)其它相關文章!

本文原創(chuàng)發(fā)布php中文網(wǎng),轉(zhuǎn)載請注明出處,感謝您的尊重!

總結(jié)

以上是生活随笔為你收集整理的python停止线程池_详解python中Threadpool线程池任务终止示例代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。