python 線程的暫停, 恢復(fù), 退出詳解及實例
python 線程 暫停, 恢復(fù), 退出
我們都知道python中可以是threading模塊實現(xiàn)多線程, 但是模塊并沒有提供暫停, 恢復(fù)和停止線程的方法, 一旦線程對象調(diào)用start方法后, 只能等到對應(yīng)的方法函數(shù)運行完畢. 也就是說一旦start后, 線程就屬于失控狀態(tài). 不過, 我們可以自己實現(xiàn)這些. 一般的方法就是循環(huán)地判斷一個標志位, 一旦標志位到達到預(yù)定的值, 就退出循環(huán). 這樣就能做到退出線程了. 但暫停和恢復(fù)線程就有點難了, 我一直也不清除有什么好的方法, 直到我看到threading中Event對象的wait方法的描述時.
wait([timeout]) Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs. 阻塞, 直到內(nèi)部的標志位為True時. 如果在內(nèi)部的標志位在進入時為True時, 立即返回. 否則, 阻塞直到其他線程調(diào)用set()方法將標準位設(shè)為True, 或者到達了可選的timeout時間. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out. 當(dāng)給定了timeout參數(shù)且不為None, 它應(yīng)該是一個浮點數(shù),以秒為單位指定操作的超時(或是分數(shù))。 此方法在退出時返回內(nèi)部標志,因此除非給定了超時且操作超時,否則它將始終返回True。 Changed in version 2.7: Previously, the method always returned None. 2.7版本以前, 這個方法總會返回None.
利用wait的阻塞機制, 就能夠?qū)崿F(xiàn)暫停和恢復(fù)了, 再配合循環(huán)判斷標識位, 就能實現(xiàn)退出了, 下面是代碼示例:
#!/usr/bin/env python
# coding: utf-8
import threading
import time
class Job(threading.Thread):
def __init__(self, *args, **kwargs):
super(Job, self).__init__(*args, **kwargs)
self.__flag = threading.Event() # 用于暫停線程的標識
self.__flag.set() # 設(shè)置為True
self.__running = threading.Event() # 用于停止線程的標識
self.__running.set() # 將running設(shè)置為True
def run(self):
while self.__running.isSet():
self.__flag.wait() # 為True時立即返回, 為False時阻塞直到內(nèi)部的標識位為True后返回
print time.time()
time.sleep(1)
def pause(self):
self.__flag.clear() # 設(shè)置為False, 讓線程阻塞
def resume(self):
self.__flag.set() # 設(shè)置為True, 讓線程停止阻塞
def stop(self):
self.__flag.set() # 將線程從暫停狀態(tài)恢復(fù), 如何已經(jīng)暫停的話
self.__running.clear() # 設(shè)置為False
下面是測試代碼:
a = Job() a.start() time.sleep(3) a.pause() time.sleep(3) a.resume() time.sleep(3) a.pause() time.sleep(2) a.stop()
測試的結(jié)果:

這完成了暫停, 恢復(fù)和停止的功能. 但是這里有一個缺點: 無論是暫停還是停止, 都不是瞬時的, 必須等待run函數(shù)內(nèi)部的運行到達標志位判斷時才有效. 也就是說操作會滯后一次.
但是這有時也不一定是壞事. 如果run函數(shù)中涉及了文件操作或數(shù)據(jù)庫操作等, 完整地運行一次后再退出, 反而能夠執(zhí)行剩余的資源釋放操作的代碼(例如各種close). 不會出現(xiàn)程序的文件操作符超出上限, 數(shù)據(jù)庫連接未釋放等尷尬的情況.
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Python通過zookeeper實現(xiàn)分布式服務(wù)代碼解析
這篇文章主要介紹了Python通過zookeeper實現(xiàn)分布式服務(wù)代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07
python和Appium移動端多設(shè)備自動化測試框架實現(xiàn)
這篇文章主要介紹了python和Appium移動端多設(shè)備自動化測試框架實現(xiàn),基于pytest和Appium框架,支持Android和iOS功能自動化的測試框架的相關(guān)內(nèi)容,需要的小伙伴可以參考一下2022-04-04
Python3中在Anaconda環(huán)境下安裝basemap包
今天小編就為大家分享一篇關(guān)于Python3中在Anaconda環(huán)境下安裝basemap包的文章,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10

