我可以暂停和继续的线程?

我可以暂停和继续的线程?,第1张

我可以暂停和继续的线程

Condition
可以用于。

这是填写您的骨骼示例

class Me(threading.Thread):    def __init__(self):        threading.Thread.__init__(self)        #flag to pause thread        self.paused = False        # Explicitly using Lock over RLock since the use of self.paused        # break reentrancy anyway, and I believe using Lock could allow        # one thread to pause the worker, while another resumes; haven't        # checked if Condition imposes additional limitations that would         # prevent that. In Python 2, use of Lock instead of RLock also        # boosts performance.        self.pause_cond = threading.Condition(threading.Lock())    def run(self):        while True: with self.pause_cond:     while self.paused:         self.pause_cond.wait()     #thread should do the thing if     #not paused     print 'do the thing' time.sleep(5)    def pause(self):        self.paused = True        # If in sleep, we acquire immediately, otherwise we wait for thread        # to release condition. In race, worker will still see self.paused        # and begin waiting until it's set back to False        self.pause_cond.acquire()    #should just resume the thread    def resume(self):        self.paused = False        # Notify so thread will wake after lock released        self.pause_cond.notify()        # Now release the lock        self.pause_cond.release()

希望能有所帮助。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5623571.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存