Pause and resume flow in python

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

How can i do this?

+4
source share
1 answer

Remember that using threads in Pythin will not give you parallel processing, except in the case of blocking I / O. See this and this for more information.

Thread Python ( , ). , (, pure-C). , , , . :

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()

, :

  • Threading - , , , , .
  • , . , , , Thread (, self._event.wait()).
  • , , , . .

. , , , , :

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(), .

, :

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).

+6

Source: https://habr.com/ru/post/1679280/


All Articles