搜尋
首頁後端開發Python教學python 執行緒的暫停, 恢復, 退出詳解及實例

python 線程暫停, 恢復, 退出

#我們都知道python中可以是threading模組實現多線程, 但是模組並沒有提供暫停, 恢復和停止線程的方法, 一旦線程物件調用start方法後, 只能等到對應的方法函數運行完畢. 也就是說一旦start後, 線程就屬於失控狀態. 不過, 我們可以自己實現這些. 一般的方法就是循環地判斷一個標誌位, 一旦標誌位到達到預定的值, 就退出循環. 這樣就能做到退出線程了. 但暫停和恢復線程就有點難了, 我一直也不清除有什麼好的方法, 直到我看到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.

  阻塞, 直到内部的标志位为True时. 如果在内部的标志位在进入时为True时, 立即返回. 否则, 阻塞直到其他线程调用set()方法将标准位设为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.

  当给定了timeout参数且不为None, 它应该是一个浮点数,以秒为单位指定操作的超时(或是分数)。

  此方法在退出时返回内部标志,因此除非给定了超时且操作超时,否则它将始终返回True。

  Changed in version 2.7: Previously, the method always returned None.

  2.7版本以前, 这个方法总会返回None.



  利用wait的阻塞機制, 就能夠實現暫停和恢復了, 再配合循環判斷識別位元, 就能實現退出了, 下面是程式碼範例:

#!/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()    # 设置为True
    self.__running = threading.Event()   # 用于停止线程的标识
    self.__running.set()   # 将running设置为True

  def run(self):
    while self.__running.isSet():
      self.__flag.wait()   # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回
      print time.time()
      time.sleep(1)

  def pause(self):
    self.__flag.clear()   # 设置为False, 让线程阻塞

  def resume(self):
    self.__flag.set()  # 设置为True, 让线程停止阻塞

  def stop(self):
    self.__flag.set()    # 将线程从暂停状态恢复, 如何已经暂停的话
    self.__running.clear()    # 设置为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()



測試的結果:


python 執行緒的暫停, 恢復, 退出詳解及實例

  這完成了暫停, 恢復和停止的功能. 但是這裡有一個缺點: 無論是暫停還是停止, 都不是瞬時的, 必須等待run函數內部的運行到達標誌位判斷時才有效. 也就是說操作會滯後一次.

  但是這有時也不一定是壞事. 如果run函數中涉及了文件操作或資料庫操作等, 完整地運行一次後再退出, 反而能夠執行剩餘的資源釋放操作的代碼(例如各種close). 不會出現程序的文件操作符超出上限, 數據庫連接未釋放等尷尬的情況.

以上是python 執行緒的暫停, 恢復, 退出詳解及實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使用numpy創建多維數組?如何使用numpy創建多維數組?Apr 29, 2025 am 12:27 AM

使用NumPy創建多維數組可以通過以下步驟實現:1)使用numpy.array()函數創建數組,例如np.array([[1,2,3],[4,5,6]])創建2D數組;2)使用np.zeros(),np.ones(),np.random.random()等函數創建特定值填充的數組;3)理解數組的shape和size屬性,確保子數組長度一致,避免錯誤;4)使用np.reshape()函數改變數組形狀;5)注意內存使用,確保代碼清晰高效。

說明Numpy陣列中'廣播”的概念。說明Numpy陣列中'廣播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增強可讀性,和Boostsperformance.Shere'shore'showitworks:1)較小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

舉一個場景的示例,其中使用Python列表比使用數組更合適。舉一個場景的示例,其中使用Python列表比使用數組更合適。Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

您如何在Python數組中訪問元素?您如何在Python數組中訪問元素?Apr 29, 2025 am 12:11 AM

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Apr 28, 2025 pm 04:34 PM

文章討論了由於語法歧義而導致的Python中元組理解的不可能。建議使用tuple()與發電機表達式使用tuple()有效地創建元組。 (159個字符)

Python中的模塊和包裝是什麼?Python中的模塊和包裝是什麼?Apr 28, 2025 pm 04:33 PM

本文解釋了Python中的模塊和包裝,它們的差異和用法。模塊是單個文件,而軟件包是帶有__init__.py文件的目錄,在層次上組織相關模塊。

Python中的Docstring是什麼?Python中的Docstring是什麼?Apr 28, 2025 pm 04:30 PM

文章討論了Python中的Docstrings,其用法和收益。主要問題:Docstrings對於代碼文檔和可訪問性的重要性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)