python下載文件暫停恢復_Python關于Threading暫停恢復解決辦法

我們都知道python中可以是threading模塊實現多線程, 但是模塊并沒有提供暫停, 恢復和停止線程的方法, 一旦線程對象調用start方法后, 只能等到對應的方法函數運行完畢. 也就是說一旦start后, 線程就屬于失控狀態. 不過, 我們可以自己實現這些. 一般的方法就是循環地判斷一個標志位, 一旦標志位到達到預定的值, 就退出循環. 這樣就能做到退出線程了. 但暫停和恢復線程就有點難了, 我一直也不清除有什么好的方法, 直到我看到threading中Event對象的wait方法的描述時.

copycode.gif

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.

copycode.gif

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

copycode.gif

#!/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

copycode.gif

下面是測試代碼:

copycode.gif

a = Job()

a.start()

time.sleep(3)

a.pause()

time.sleep(3)

a.resume()

time.sleep(3)

a.pause()

time.sleep(2)

a.stop()

copycode.gif

測試的結果:

954521-20161205102357476-930411816.png

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

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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/542734.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/542734.shtml
英文地址,請注明出處:http://en.pswp.cn/news/542734.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

信息系統狀態過程圖_過程狀態圖中使用的重要術語| 操作系統

信息系統狀態過程圖1)上下文切換 (1) Context Switching) Whenever a process is transferred within the system, it moves within different states. These states are known as the process states. When a process goes from one state to another state inside the system…

mysql 吧庫下的表名都加_mysql數據庫表名大小寫問題

mysql數據庫表名大小寫問題mysql數據庫linux版本表名、字段名默認大小寫敏感,即區分大小寫。查看mysql有關大小寫參數:lower_case_file_system是一個只讀參數,無法被修改,這個參數是用來告訴你在當前的系統平臺(linux\windows等)下…

rgb 灰色_金屬+RGB+無線,我要買爆這款海盜船VIRTUOSO鑒賞家游戲耳機

海盜船最近新出的旗艦耳機,VIRTUOSO RGB Wireless SE,中文名叫鑒賞家。耳機一改往日歐美電競風,改走金屬質感高大上簡約風,不過講真,這顏值我吃起來很香。考慮文章過長,我先概括一下入手理由,具…

python 基類 派生類_在Python中具有兩個子(派生)類的繼承示例

python 基類 派生類In this program, we have a parent class named Details and two child classes named Employee and Doctor, we are inheritance the class Details on the classes Employee and Doctor. And, finally creating two objects of Employee and Doctor class…

連接postgresql

# psycopg2enginecreate_engine(postgresqlpsycopg2://scott:tigerlocalhost/mydatabase)#python 連接postgresql使用psycopg2作為默認的DBAPIThe first time a method like Engine.execute()orEngine.connect()is called, the Engine establishes a real DBAPI connection to …

n的階乘程序python_Python程序對N階乘的尾隨零進行計數

n的階乘程序pythonFormula used: 使用的公式: Trailing 0s in N! Count of 5s in prime factors of n! floor(n/5) floor(n/25) floor(n/125) ....Example: 例: Input: N 23Output: 4Factorial of 23 is 25852016738884976640000 which has four …

c mysql使用場景_Mysql 場景

1個SQL題,1個場景題,會有點難度!SQL題該SQL題大量涉及到row_number,case when,group by等高級用法,有一定的實用價值,總結出來,供日后參考Question.1:分組匯總給定篩選條…

以己為壑

2019獨角獸企業重金招聘Python工程師標準>>> 今天把軟件工程里面關于面向對象的設計學完了,使我對面向對象OOA和OOD的思想有了進一步的認識,各科知識千溝萬壑,犬牙交錯,的確是這樣,能蒙住自己眼的永遠是你自己,而不是這個世界,因為美就在那里;裹住自己雙足的的永遠是…

macos安裝vscode_如何使用VSCode進行PostgreSQL開發及調試

Visual Studio Code (VSCode)是一個輕量級但功能強大的源代碼編輯器,可在桌面上運行,適用于Windows,macOS和Linux。 它內置了對JavaScript,TypeScript和Node.js的支持,并具有豐富的其他語言(如C,C&#xff…

最小生成樹 kruskal_使用Kruskal算法求解Java最小生成樹問題

最小生成樹 kruskalIn Electronic Circuit we often required less wiring to connect pins together. We can model this wiring problem with a connected, undirected graph G(V, E), where V is the set of pins, E is the set of possible interconnections between pair …

mysql數據庫面試題 軟件測試_軟件測試數據庫面試題一

前提本次分享只局限于 sql server 和 mysql 這兩種數據庫,其他數據庫暫不總結正文1. 對查詢的字段進行去重(distinct)用法注意:1. distinct【查詢字段】,必須放在要查詢字段的開頭,即放在第一個參數;2. 只能在SELECT 語…

python數碼時鐘代碼_python時鐘的實現

from time importsleepimporttimeimportosclassClock(object):"""數字時鐘""" def __init__(self, hour0, minute0, second0):"""初始化方法 :param hour: 時 :param minute: 分 :param second: 秒"""self._hourh…

PHP頁面跳轉

本文轉載自:http://blog.sina.com.cn/s/blog_9a06890901014ol1.html PHP頁面跳轉一、header()函數 header函數中Location類型的標頭是一種特殊的header調用,常用來實現頁面跳轉 注意:1、location和“:”號間不能有空格,否則不會跳…

如何打印出給定尺寸的方格_打印給定號碼的表格| 8086微處理器

如何打印出給定尺寸的方格Problem statement: 問題陳述: Write an assembly language program in 8086 to print the table of a given integer. 在8086中編寫匯編語言程序以打印給定整數的表。 Assumptions: Suppose the inputted number is at memory location …

python自動更新excel數據_如何更新Excel數據?(刷新所有查詢)

我有一個帶有一些查詢的Excel xlsm文件。目前我每天打開它,點擊“數據”選項卡中的“全部刷新”命令。我希望這件事能自動完成。我用python編寫了一個腳本(我是python新手)。問題是,刷新數據并保存Excel文件后,刷新的數據不可見(我知道刷新工…

mongoDB 使用手冊

2019獨角獸企業重金招聘Python工程師標準>>> 1、基本操作db.AddUser(username,password) 添加用戶db.auth(usrename,password) 設置數據庫連接驗證db.cloneDataBase(fromhost) 從目標服務器克隆一個數據庫db.commandHelp(name) returns the help for the commanddb.…

android搜索框功能實現_巧用 Trie 樹,實現搜索引擎關鍵詞提示功能

來源 | 碼海責編 | Carol封圖 | CSDN 付費下載于視覺中國我們幾乎每天都在用搜索引擎搜索信息,相信大家肯定有注意過這樣一個細節:當輸入某個字符的時候,搜索引框底下會出現多個推薦詞,如下,輸入「python」后,底下會出…

Python | 從用戶輸入數據,保存到文件,讀取并打印

Here, we have to input the data from the user, to read the data from user, we use input() method, and then the input data we have to store in the file by using write() method and then by using read() method we can get the data. 在這里,我們必須從…

python語句print type 1234的輸出結果是_Python語句 print(type(1J))的輸出結果是

【填空題】遍歷輸出文件所有行。 fopen("d:\\r2.txt","r") while True: str print(str,end) if not str: break f.close()【單選題】執行下列 Python語句將產生的結果是( ) i1 if (i): print(True) else: print( False)【單選題】Python語句 print(type(1/…

qt5.9.0調試如何查看變量的值_深入了解 Java 調試

Bug(俗稱"八阿哥") 是軟件開發繞不過的一道坎,因此調試便成了每位程序員一項必備的核心技能。調試不僅有助于理解程序的運行流程,還能改進代碼質量,最終提高開發者解決問題的能力以及交付軟件的品質。本文旨在討論 Java 調試關鍵技…