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

巴扎黑
發布: 2017-03-30 14:22:09
原創
3052 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!