我正在尝试创建一个线程,该线程在后台执行操作。我需要能够在需要时有效地“暂停”并稍后再次“恢复”。另外,如果我“暂停”该线程时正在执行某项操作,则该线程应使调用线程等到完成其操作为止。
我对Python中的多线程技术还很陌生,所以我还没走那么远。
除了线程正在做某事时调用了pause之外,我几乎可以做的所有事情都让调用线程等待。
这是我要在代码中实现的目标的概述:
import threading, time class Me(threading.Thread): def __init__(self): threading.Thread.__init__(self) #flag to pause thread self.paused = False def run(self): while True: if not self.paused: #thread should do the thing if #not paused print 'do the thing' time.sleep(5) def pause(self): self.paused = True #this is should make the calling thread wait if pause() is #called while the thread is 'doing the thing', until it is #finished 'doing the thing' #should just resume the thread def resume(self): self.paused = False
我想我基本上需要一种锁定机制,但是在同一线程内?
Condition可以用于。
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()
希望能有所帮助。