阻止主线程直到python后台线程完成side-task
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了阻止主线程直到python后台线程完成side-task,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2352字,纯文字阅读大概需要4分钟。
内容图文
![阻止主线程直到python后台线程完成side-task](/upload/InfoBanner/zyjiaocheng/720/40e15e9af85b414690381482a39fd308.jpg)
我有一个线程python应用程序,后台线程中有一个长时间运行的mainloop.这个后台主循环实际上是对pyglet.app.run()的调用,它驱动一个GUI窗口,也可以配置为定期调用其他代码.我需要从主线程中随意调用do_stuff(duration)函数来触发GUI中的动画,等待动画停止,然后返回.实际动画必须在后台线程中完成,因为GUI库无法处理由单独的线程驱动.
我相信我需要做这样的事情:
import threading
class StuffDoer(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.max_n_times = 0
self.total_n_times = 0
self.paused_ev = threading.Event()
def run(self):
# this part is outside of my control
while True:
self._do_stuff()
# do other stuff
def _do_stuff(self):
# this part is under my control
if self.paused_ev.is_set():
if self.max_n_times > self.total_n_times:
self.paused_ev.clear()
else:
if self.total_n_times >= self.max_n_times:
self.paused_ev.set()
if not self.paused_ev.is_set():
# do stuff that must execute in the background thread
self.total_n_times += 1
sd = StuffDoer()
sd.start()
def do_stuff(n_times):
sd.max_n_times += n_times
sd.paused_ev.wait_for_clear() # wait_for_clear() does not exist
sd.paused_ev.wait()
assert (sd.total_n_times == sd.max_n_times)
编辑:使用max_n_times而不是stop_time来阐明为什么Thread.join(持续时间)不会这样做.
从threading.Event的文档:
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.
我发现如果我有一对事件paused_ev和not_paused_ev,并且使用not_paused_ev.wait(),我可以得到我正在寻找的行为.我几乎只能使用Thread.join(持续时间),除非它只需要在后台线程实际注册时间到时才精确返回.我应该使用其他同步对象或其他策略吗?
我也愿意接受这样的论点,即如果他们是一个好的论据,那么我正以错误的方式接近这一切.
解决方法:
希望我从我的评论中获得一些修订或其他信息,但我有点想知道你是不是通过继承Thread来过度工作.你可以做这样的事情:
class MyWorker(object):
def __init__(self):
t = Thread(target = self._do_work, name "Worker Owned Thread")
t.daemon = True
t.start()
def _do_work(self):
While True:
# Something going on here, forever if necessary. This thread
# will go away if the other non-daemon threads terminate, possibly
# raising an exception depending this function's body.
我发现当你想要运行的方法更适合某个其他类的成员函数而不是作为线程上的run方法时,这更有意义.此外,这使您不必在Thread内部封装一堆业务逻辑.当然,所有IMO.
内容总结
以上是互联网集市为您收集整理的阻止主线程直到python后台线程完成side-task全部内容,希望文章能够帮你解决阻止主线程直到python后台线程完成side-task所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。