python – 我可以暂停和恢复的线程?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 我可以暂停和恢复的线程?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2055字,纯文字阅读大概需要3分钟。
内容图文
![python – 我可以暂停和恢复的线程?](/upload/InfoBanner/zyjiaocheng/709/d704c2eb16c840f0a89d28fe1a0fee2d.jpg)
我正在尝试创建一个在后台执行操作的线程.我需要能够在需要时有效地“暂停”它,并在以后再次“恢复”它.此外,如果线程在我“暂停”它时正在做某事,它应该让调用线程等到它完成它正在做的事情.
我对Python中的多线程很新,所以我还没有那么远.
除了让调用线程等待,如果在我的线程正在执行某些操作时调用暂停,我几乎可以做的事情.
以下是我在代码中尝试实现的概述:
import threading, time
class Me(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
#flag to pause thread
self.paused = False
def run(self):
while True:
if not self.paused:
#thread should do the thing if
#not paused
print 'do the thing'
time.sleep(5)
def pause(self):
self.paused = True
#this is should make the calling thread wait if pause() is
#called while the thread is 'doing the thing', until it is
#finished 'doing the thing'
#should just resume the thread
def resume(self):
self.paused = False
我想我基本上需要一个锁定机制,但在同一个线程内?
解决方法:
Conditions can be used for this.
以下是填充骨架的示例:
class Me(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
#flag to pause thread
self.paused = False
# Explicitly using Lock over RLock since the use of self.paused
# break reentrancy anyway, and I believe using Lock could allow
# one thread to pause the worker, while another resumes; haven't
# checked if Condition imposes additional limitations that would
# prevent that. In Python 2, use of Lock instead of RLock also
# boosts performance.
self.pause_cond = threading.Condition(threading.Lock())
def run(self):
while True:
with self.pause_cond:
while self.paused:
self.pause_cond.wait()
#thread should do the thing if
#not paused
print 'do the thing'
time.sleep(5)
def pause(self):
self.paused = True
# If in sleep, we acquire immediately, otherwise we wait for thread
# to release condition. In race, worker will still see self.paused
# and begin waiting until it's set back to False
self.pause_cond.acquire()
#should just resume the thread
def resume(self):
self.paused = False
# Notify so thread will wake after lock released
self.pause_cond.notify()
# Now release the lock
self.pause_cond.release()
希望有所帮助.
内容总结
以上是互联网集市为您收集整理的python – 我可以暂停和恢复的线程?全部内容,希望文章能够帮你解决python – 我可以暂停和恢复的线程?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。