python多线程控制暂停_python中的多线程编程与暂停、播放音频的结合
发布日期:2021-11-19 18:35:38 浏览次数:6 分类:技术文章

本文共 1324 字,大约阅读时间需要 4 分钟。

我们都知道python中可以是threading模块实现多线程, 但是模块并没有提供暂停, 恢复和停止线程的方法, 一旦线程对象调用start方法后, 只能等到对应的方法函数运行完毕. 也就是说一旦start后, 线程就属于失控状态. 不过, 我们可以自己实现这些. 一般的方法就是循环地判断一个标志位, 一旦标志位到达到预定的值, 就退出循环. 这样就能做到退出线程了. 但暂停和恢复线程就有点难了, 我一直也不清除有什么好的方法, 直到我看到threading中Event对象的wait方法的描述时.

复制代码

wait([timeout])

Block until the internal flagis true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, oruntil the optional timeout occurs.

阻塞, 直到内部的标志位为True时. 如果在内部的标志位在进入时为True时, 立即返回. 否则, 阻塞直到其他线程调用set()方法将标准位设为True, 或者到达了可选的timeout时间.

When the timeout argumentis present and not None, it should be a floating point number specifying a timeout for the operation in seconds (orfractions thereof).

This method returns the internal flag on exit, so it will alwaysreturn True except if a timeout is given andthe operation times out.

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

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

Changedin version 2.7: Previously, the method always returned None.2.7版本以前, 这个方法总会返回None.

复制代码

利用wait的阻塞机制, 就能够实现暂停和恢复了, 再配合循环判断标识位, 就能实现退出了, 下面是代码示例:

这完成了暂停, 恢复和停止的功能. 但是这里有一个缺点: 无论是暂停还是停止, 都不是瞬时的, 必须等待run函数内部的运行到达标志位判断时才有效. 也就是说操作会滞后一次.

但是这有时也不一定是坏事. 如果run函数中涉及了文件操作或数据库操作等, 完整地运行一次后再退出, 反而能够执行剩余的资源释放操作的代码(例如各种close). 不会出现程序的文件操作符超出上限, 数据库连接未释放等尴尬的情况.

转载地址:https://blog.csdn.net/weixin_39927214/article/details/110065678 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:python协程使用场景_python协程
下一篇:python的实例属性和静态属性_Python中的类属性、实例属性与类方法、静态方法

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月16日 06时54分49秒