• 正文
    • 需求
    • 多線程
    • 多進(jìn)程
    • 多協(xié)程
    • 結(jié)語(yǔ)
  • 相關(guān)推薦
申請(qǐng)入駐 產(chǎn)業(yè)圖譜

python中強(qiáng)制關(guān)閉線程、協(xié)程、進(jìn)程方法

03/13 11:03
1164
加入交流群
掃碼加入
獲取工程師必備禮包
參與熱點(diǎn)資訊討論
python使用中多線程、多進(jìn)程、多協(xié)程使用是比較常見(jiàn)的。那么如果在多線程等的使用,我們這個(gè)時(shí)候我們想從外部強(qiáng)制殺掉該線程請(qǐng)問(wèn)如何操作?下面我就分享一下我的執(zhí)行看法:

歡迎關(guān)注微信公眾號(hào):羽林君,或者添加作者個(gè)人微信:become_me

需求

在python多線程等的使用中,我們需要在外部強(qiáng)制終止線程,這個(gè)時(shí)候又沒(méi)有unix的pthread kill的函數(shù),多進(jìn)程這個(gè)時(shí)候大家覺(jué)得可以使用kill -9 直接強(qiáng)制殺掉就可以了,從邏輯上這么做沒(méi)問(wèn)題,但是不太優(yōu)雅。其中我總結(jié)了一下不僅是使用多線程,以及多協(xié)程、多進(jìn)程在python的實(shí)現(xiàn)對(duì)比。

此外也可以參考stackoverlow的文章,如何優(yōu)雅的關(guān)閉一個(gè)線程,里面有很多的討論,大家可以閱讀一下

下面是網(wǎng)址:https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread

開(kāi)始進(jìn)入正題:

多線程

首先線程中進(jìn)行退出的話,我們經(jīng)常會(huì)使用一種方式:子線程執(zhí)行的循環(huán)條件設(shè)置一個(gè)條件,當(dāng)我們需要退出子線程的時(shí)候,將該條件置位,這個(gè)時(shí)候子線程會(huì)主動(dòng)退出,但是當(dāng)子線程處于阻塞情況下,沒(méi)有在循環(huán)中判斷條件,并且阻塞時(shí)間不定的情況下,我們回收該線程也變得遙遙無(wú)期。這個(gè)時(shí)候就需要下面的幾種方式出馬了:

守護(hù)線程:

如果你設(shè)置一個(gè)線程為守護(hù)線程,就表示你在說(shuō)這個(gè)線程是不重要的,在進(jìn)程退出的時(shí)候,不用等待這個(gè)線程退出。如果你的主線程在退出的時(shí)候,不用等待那些子線程完成,那就設(shè)置這些線程的daemon屬性。即,在線程開(kāi)始(thread.start())之前,調(diào)用setDeamon()函數(shù),設(shè)定線程的daemon標(biāo)志。(thread.setDaemon(True))就表示這個(gè)線程“不重要”。

如果你想等待子線程完成再退出,那就什么都不用做。,或者顯示地調(diào)用thread.setDaemon(False),設(shè)置daemon的值為false。新的子線程會(huì)繼承父線程的daemon標(biāo)志。整個(gè)Python會(huì)在所有的非守護(hù)線程退出后才會(huì)結(jié)束,即進(jìn)程中沒(méi)有非守護(hù)線程存在的時(shí)候才結(jié)束。

也就是子線程為非deamon線程,主線程不立刻退出

import?threading
import?time
import?gc
import?datetime

def?circle():
????print("begin")
????try:
????????while?True:
????????????current_time?=?datetime.datetime.now()
????????????print(str(current_time)?+?'?circle.................')
????????????time.sleep(3)
????except?Exception?as?e:
????????print('error:',e)
????finally:
????????print('end')


if?__name__?==?"__main__":
???t?=?threading.Thread(target=circle)
???t.setDaemon(True)
???t.start()
???time.sleep(1)
???#?stop_thread(t)
???#?print('stoped?threading?Thread')?
???current_time?=?datetime.datetime.now()
???print(str(current_time)?+?'?stoped?after')?
???gc.collect()
???while?True:
??????time.sleep(1)
??????current_time?=?datetime.datetime.now()
??????print(str(current_time)?+?'?end?circle')?

是否是主線程進(jìn)行控制?

守護(hù)線程需要主線程退出才能完成子線程退出,下面是代碼,再封裝一層進(jìn)行驗(yàn)證是否需要主線程退出

def?Daemon_thread():
???circle_thread=?threading.Thread(target=circle)
#????circle_thread.daemon?=?True
???circle_thread.setDaemon(True)
???circle_thread.start()???
???while?running:
????????print('running:',running)?
????????time.sleep(1)
???print('end..........')?


if?__name__?==?"__main__":
????t?=?threading.Thread(target=Daemon_thread)
????t.start()???
????time.sleep(3)
????running?=?False
????print('stop?running:',running)?
????print('stoped?3')?
????gc.collect()
????while?True:
????????time.sleep(3)
????????print('stoped?circle')?

替換main函數(shù)執(zhí)行,發(fā)現(xiàn)打印了 stoped 3這個(gè)標(biāo)志后circle線程還在繼續(xù)執(zhí)行。

結(jié)論:處理信號(hào)靠的就是主線程,只有保證他活著,信號(hào)才能正確處理。

在 Python 線程中引發(fā)異常

雖然使用PyThreadState_SetAsyncExc大部分情況下可以滿足我們直接退出線程的操作;但是PyThreadState_SetAsyncExc方法只是為線程退出執(zhí)行“計(jì)劃”。它不會(huì)殺死線程,尤其是當(dāng)它正在執(zhí)行外部 C 庫(kù)時(shí)。嘗試sleep(100)用你的方法殺死一個(gè)。它將在 100 秒后被“殺死”。while flag:它與->flag = False方法一樣有效。

所以子線程有例如sleep等阻塞函數(shù)時(shí)候,在休眠過(guò)程中,子線程無(wú)法響應(yīng),會(huì)被主線程捕獲,導(dǎo)致無(wú)法取消子線程。就是實(shí)際上當(dāng)線程休眠時(shí)候,直接使用async_raise 這個(gè)函數(shù)殺掉線程并不可以,因?yàn)槿绻€程在 Python 解釋器之外忙,它就不會(huì)捕獲中斷

示例代碼:

import?ctypes
import?inspect
import?threading
import?time
import?gc
import?datetime

def?async_raise(tid,?exctype):
???"""raises?the?exception,?performs?cleanup?if?needed"""
???tid?=?ctypes.c_long(tid)
???if?not?inspect.isclass(exctype):
??????exctype?=?type(exctype)
???res?=?ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,?ctypes.py_object(exctype))
???if?res?==?0:
??????raise?ValueError("invalid?thread?id")
???elif?res?!=?1:
??????#?"""if?it?returns?a?number?greater?than?one,?you're?in?trouble,??
??????#?and?you?should?call?it?again?with?exc=NULL?to?revert?the?effect"""??
??????ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,?None)
??????raise?SystemError("PyThreadState_SetAsyncExc?failed")
??????
def?stop_thread(thread):
???async_raise(thread.ident,?SystemExit)
???
def?circle():
????print("begin")
????try:
????????while?True:
????????????current_time?=?datetime.datetime.now()
????????????print(str(current_time)?+?'?circle.................')
????????????time.sleep(3)
????except?Exception?as?e:
????????print('error:',e)
????finally:
????????print('end')

if?__name__?==?"__main__":
???t?=?threading.Thread(target=circle)
???t.start()
???time.sleep(1)
???stop_thread(t)
???print('stoped?threading?Thread')?
???current_time?=?datetime.datetime.now()
???print(str(current_time)?+?'?stoped?after')?
???gc.collect()
???while?True:
??????time.sleep(1)
??????current_time?=?datetime.datetime.now()
??????print(str(current_time)?+?'?end?circle')?

signal.pthread_kill操作:

這個(gè)是最接近與 unix中pthread kill操作,網(wǎng)上看到一些使用,但是自己驗(yàn)證時(shí)候沒(méi)有找到這個(gè)庫(kù)里面的使用,

這是在python官方的signal解釋文檔里面的描述,看到是3.3 新版功能,我自己本身是python3.10,沒(méi)有pthread_kill,可能是后續(xù)版本又做了去除。

這是網(wǎng)上看到的一些示例代碼,但是沒(méi)法執(zhí)行,如果有人知道使用可以進(jìn)行交流。

from?signal?import?pthread_kill,?SIGTSTP
from?threading?import?Thread
from?itertools?import?count
from?time?import?sleep

def?target():
????for?num?in?count():
????????print(num)
????????sleep(1)

thread?=?Thread(target=target)
thread.start()
sleep(5)
signal.pthread_kill(thread.ident,?SIGTSTP)

多進(jìn)程

multiprocessing 是一個(gè)支持使用與 threading 模塊類似的 API 來(lái)產(chǎn)生進(jìn)程的包。multiprocessing 包同時(shí)提供了本地和遠(yuǎn)程并發(fā)操作,通過(guò)使用子進(jìn)程而非線程有效地繞過(guò)了 全局解釋器鎖。因此,multiprocessing 模塊允許程序員充分利用給定機(jī)器上的多個(gè)處理器。

其中使用了multiprocess這些庫(kù),我們可以調(diào)用它內(nèi)部的函數(shù)terminate幫我們釋放。例如t.terminate(),這樣就可以強(qiáng)制讓子進(jìn)程退出了。

不過(guò)使用了多進(jìn)程數(shù)據(jù)的交互方式比較繁瑣,得使用共享內(nèi)存、pipe或者消息隊(duì)列這些進(jìn)行子進(jìn)程和父進(jìn)程的數(shù)據(jù)交互。

示例代碼如下:

import?time
import?gc
import?datetime
import?multiprocessing

def?circle():
????print("begin")
????try:
????????while?True:
????????????current_time?=?datetime.datetime.now()
????????????print(str(current_time)?+?'?circle.................')
????????????time.sleep(3)
????except?Exception?as?e:
????????print('error:',e)
????finally:
????????print('end')


if?__name__?==?"__main__":
????t?=?multiprocessing.Process(target=circle,?args=())
????t.start()
????#?Terminate?the?process
????current_time?=?datetime.datetime.now()
????print(str(current_time)?+?'?stoped?before')?
????time.sleep(1)
????t.terminate()??#?sends?a?SIGTERM
????current_time?=?datetime.datetime.now()
????print(str(current_time)?+?'?stoped?after')?
????gc.collect()
????while?True:
????????time.sleep(3)
????????current_time?=?datetime.datetime.now()
????????print(str(current_time)?+?'?end?circle')?

多協(xié)程

協(xié)程(coroutine)也叫微線程,是實(shí)現(xiàn)多任務(wù)的另一種方式,是比線程更小的執(zhí)行單元,一般運(yùn)行在單進(jìn)程和單線程上。因?yàn)樗詭?a class="article-link" target="_blank" href="/baike/1552575.html">CPU的上下文,它可以通過(guò)簡(jiǎn)單的事件循環(huán)切換任務(wù),比進(jìn)程和線程的切換效率更高,這是因?yàn)檫M(jìn)程和線程的切換由操作系統(tǒng)進(jìn)行。

Python實(shí)現(xiàn)協(xié)程的主要借助于兩個(gè)庫(kù):asyncioasyncio 是從Python3.4引入的標(biāo)準(zhǔn)庫(kù),直接內(nèi)置了對(duì)協(xié)程異步IO的支持。asyncio 的編程模型本質(zhì)是一個(gè)消息循環(huán),我們一般先定義一個(gè)協(xié)程函數(shù)(或任務(wù)), 從 asyncio 模塊中獲取事件循環(huán)loop,然后把需要執(zhí)行的協(xié)程任務(wù)(或任務(wù)列表)扔到 loop中執(zhí)行,就實(shí)現(xiàn)了異步IO)和geventGevent 是一個(gè)第三方庫(kù),可以輕松通過(guò)gevent實(shí)現(xiàn)并發(fā)同步或異步編程,在gevent中用到的主要模式是Greenlet, 它是以C擴(kuò)展模塊形式接入Python的輕量級(jí)協(xié)程。)。

由于asyncio已經(jīng)成為python的標(biāo)準(zhǔn)庫(kù)了無(wú)需pip安裝即可使用,這意味著asyncio作為Python原生的協(xié)程實(shí)現(xiàn)方式會(huì)更加流行。本文僅會(huì)介紹asyncio模塊的退出使用。

使用協(xié)程取消,有兩個(gè)重要部分:第一,替換舊的休眠函數(shù)為多協(xié)程的休眠函數(shù);第二取消使用cancel()函數(shù)。

其中cancel() 返回值為 True 表示 cancel 成功。

示例代碼如下:創(chuàng)建一個(gè)coroutine,然后調(diào)用run_until_complete()來(lái)初始化并啟動(dòng)服務(wù)器來(lái)調(diào)用main函數(shù),判斷協(xié)程是否執(zhí)行完成,因?yàn)樵O(shè)置的num協(xié)程是一個(gè)死循環(huán),所以一直沒(méi)有執(zhí)行完,如果沒(méi)有執(zhí)行完直接使用 cancel()取消掉該協(xié)程,最后執(zhí)行成功。

import?asyncio
import?time


async?def?num(n):
????try:
????????i?=?0
????????while?True:
????????????print(f'i={i}?Hello')
????????????i=i+1
????????????#?time.sleep(10)
????????????await?asyncio.sleep(n*0.1)
????????return?n
????except?asyncio.CancelledError:
????????print(f"數(shù)字{n}被取消")
????????raise


async?def?main():
????#?tasks?=?[num(i)?for?i?in?range(10)]
????tasks?=?[num(10)]
????complete,?pending?=?await?asyncio.wait(tasks,?timeout=0.5)
????for?i?in?complete:
????????print("當(dāng)前數(shù)字",i.result())
????if?pending:
????????print("取消未完成的任務(wù)")
????????for?p?in?pending:
????????????p.cancel()


if?__name__?==?'__main__':
????loop?=?asyncio.get_event_loop()
????try:
????????loop.run_until_complete(main())
????finally:
????????loop.close()

結(jié)語(yǔ)

這就是我自己的一些python 強(qiáng)制關(guān)閉線程、協(xié)程、進(jìn)程的使用分享。如果大家有更好的想法和需求,也歡迎大家加我好友交流分享哈。

參考文章:在思考如何強(qiáng)制關(guān)掉一個(gè)子線程或者子進(jìn)程亦或者協(xié)程時(shí)候看了好多文章,python相關(guān)的很多信息,方便大家更細(xì)節(jié)的查看,我把鏈接放置在下方:

https://zhuanlan.zhihu.com/p/101199579
https://blog.csdn.net/waple_0820/article/details/93026922
https://zhuanlan.zhihu.com/p/68043798
https://blog.csdn.net/u012063703/article/details/51601579
http://tylderen.github.io/linux-multi-thread-signal
https://codeantenna.com/a/qtHjqJ7TWx
https://blog.csdn.net/HighDS/article/details/103867368
https://blog.51cto.com/u_13918080/3069098
https://blog.css8.cn/post/18797088.html

作者:良知猶存,白天努力工作,晚上原創(chuàng)公號(hào)號(hào)主。公眾號(hào)內(nèi)容除了技術(shù)還有些人生感悟,一個(gè)認(rèn)真輸出內(nèi)容的職場(chǎng)老司機(jī),也是一個(gè)技術(shù)之外豐富生活的人,攝影、音樂(lè) and 籃球。關(guān)注我,與我一起同行。

相關(guān)推薦

登錄即可解鎖
  • 海量技術(shù)文章
  • 設(shè)計(jì)資源下載
  • 產(chǎn)業(yè)鏈客戶資源
  • 寫(xiě)文章/發(fā)需求
立即登錄

一個(gè)程序員,喜歡寫(xiě)文章,還喜歡打籃球,也喜歡吉他鋼琴的駁雜之人。日常更新自己,分享包括但不限于C/C++、嵌入式、物聯(lián)網(wǎng)、Linux等編程學(xué)習(xí)筆記,同時(shí),公眾號(hào)內(nèi)包含大量的學(xué)習(xí)資源。歡迎關(guān)注,一同交流學(xué)習(xí),共同進(jìn)步!