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.mzph.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 调试关键技…