本文介绍了在python中暂停和恢复线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要暂停和恢复线程,该线程不断执行某些任务.执行在start()被调用时开始,不能中断,必须从pause()被调用时开始执行.

I need to pause and resume thread, which continuously executes some task. Execution begins when start() is called, it should not be interrupted and must continue from the point when pause() is called.

我该怎么做?

推荐答案

请记住,在 Pythin 中使用线程不会授予您并行处理,除非 IO 阻塞操作的情况.有关这方面的更多信息,请查看 thisthis

您不能在 Python 中任意暂停线程(在进一步阅读之前请记住这一点).我不确定你有没有办法在操作系统级别做到这一点(例如,通过使用纯 C).您可以做的是允许线程在您事先考虑的特定点暂停.我给你举个例子:

You cannot pause a Thread arbitrarily in Python (please keep that in mind before reading further). I am neither sure you have a way to do that at an OS level (e.g. by using pure-C). What you can do is allow the thread to be paused at specific points you consider beforehand. I will give you an example:

class MyThread(threading.Thread):

    def __init__(self, *args, **kwargs):
        super(MyThread, self).__init__(*args, **kwargs)
        self._event = threading.Event()

    def run(self):
        while True:
            self.foo() # please, implement this.
            self._event.wait()
            self.bar() # please, implement this.
            self._event.wait()
            self.baz() # please, implement this.
            self._event.wait()

    def pause(self):
        self._event.clear()

    def resume(self):
        self._event.set()

这种方法可行,但:

  • 根据我给您的链接,线程通常是个坏主意.
  • 您必须使用这种方法自己编写 run 方法.这是因为您需要控制要检查暂停的确切点,这意味着访问 Thread 对象(也许您想创建一个额外的方法而不是调用 self._event.wait()).
  • 前一点清楚地表明您不能随意暂停,但只有在您指定时才可以暂停.避免在暂停点之间进行长时间操作.

编辑我没有测试这个,但如果你需要多个这样的线程,也许这会在没有这么多子类的情况下工作:

Edit I did not test this one, but perhaps this will work without so much subclassing if you need more than one thread like this:

class MyPausableThread(threading.Thread):

    def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
        self._event = threading.Event()
        if target:
            args = (self,) + args
        super(MyPausableThread, self).__init__(group, target, name, args, kwargs)

    def pause(self):
        self._event.clear()

    def resume(self):
        self._event.set()

    def _wait_if_paused(self):
        self._event.wait()

这应该允许您通过调用 MyPausableThread(target=myfunc).start() 创建一个没有更多子类化的自定义线程,并且您的可调用对象的第一个参数将接收线程对象,您可以从中获取需要暂停检查时可以调用self._wait_if_paused().

This should allow you to create a custom thread without more subclassing, by calling MyPausableThread(target=myfunc).start(), and your callable's first parameter will receive the thread object, from which you can call self._wait_if_paused() when you need to pause-check.

或者更好,如果你想隔离目标访问线程对象:

Or even better, if you want to isolate the target from accessing the thread object:

class MyPausableThread(threading.Thread):

    def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
        self._event = threading.Event()
        if target:
            args = ((lambda: self._event.wait()),) + args
        super(MyPausableThread, self).__init__(group, target, name, args, kwargs)

    def pause(self):
        self._event.clear()

    def resume(self):
        self._event.set()

并且您的目标可调用对象将在第一个参数中接收一个可以像这样调用的函数:pause_checker()(假设目标可调用对象中的第一个参数名为 pause_checker>).

And your target callable will receive in the first parameter a function that can be called like this: pause_checker() (provided the first param in the target callable is named pause_checker).

这篇关于在python中暂停和恢复线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:20
查看更多