Thread that I can pause and resume?

后端 未结 2 1022
北恋
北恋 2020-11-28 11:38

I\'m trying to create a thread, that does stuff in the background. I need to be able to effectively \'pause\' it when I need to and \'resume\' it again later. Also, if the t

2条回答
  •  一个人的身影
    2020-11-28 11:54

    Use threading.Event instead of a boolean variable, and add another event for busy state:

    def __init__(self):
        ...
        self.can_run = threading.Event()
        self.thing_done = threading.Event()
        self.thing_done.set()
        self.can_run.set()    
    
    def run(self):
        while True:
            self.can_run.wait()
            try:
                self.thing_done.clear()
                print 'do the thing'
            finally:
                self.thing_done.set()
    
    def pause(self):
        self.can_run.clear()
        self.thing_done.wait()
    
    def resume(self):
        self.can_run.set()
    

    edit: previous answer was wrong, I fixed it and changed variable names to be clear

提交回复
热议问题