简体   繁体   中英

How to pause and resume a thread in python

I make a thread to run a script, and it may spend much time. And I want to pause and resume it in another thread. If I use a flag and detect it, it can not pause immediately. I have searched a lot, but it seems that self.__flag, self.pause can not achieve the target.

class MT(threading.Thread):

    def __init__():
        self.__running = threading.Event()
        self.__running.set()
        self.__flag = threading.Event()
        self.__flag.set()

    def run(self):
        '''
        run the script
        '''
        while self.__running.isSet():
             self.__flag.wait()
             moudleTest()

    def pause(self):
        '''
        pause the thread
        '''
        self.__flag.clear()

    def resume(self):
        '''
        resume the thread
        '''
        self._-flag.set()

What you want is not possible without diving below the Python layer using C extensions with OS specific techniques, eg on Windows, SuspendThread . You can not immediately and completely suspend another thread via Python level APIs, because doing so is considered absurdly dangerous.

Even when such a thing is possible, it's a terrible idea, prone to deadlocks and other terrible things. Just for example, pre-CPython 3.3, there was a single global import lock for the whole interpreter. If the other thread was in the middle of import ing a module when it was suspended, no other thread could import at all until it was resumed and finished the import (causing a deadlock if that thread was the one responsible for resuming the suspended thread); in CPython 3.3+, it's better, but if another thread tried to import that specific module, it would deadlock just as badly.

In summary: Use Lock s, Event s and/or Condition s appropriately, and if you need faster pauses, make the wait checks more often (interspersed with thread "work" more regularly). If your code can't tolerate even a tiny delay before the pause, you have a design problem that you need to fix (eg you're using Event to simulate locking or the like, possibly for performance, which is hilariously misguided, since Event s are built on Condition s which are in turn built on Lock s, and all but Lock are implemented at the Python layer, not the C layer, and therefore quite slow).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM