我想创建一个线程,在后台执行某些任务。当需要时,我需要能够有效地“暂停”它,并在稍后“恢复”它。此外,如果线程在执行某些任务时被“暂停”,则应该使调用线程等待直到完成。
我在Python中的多线程编程方面比较新手,所以我还没有深入了解。
基本上我已经实现了所有功能,除了当我的线程正在执行某些任务时,调用线程不能等待暂停被调用。
这是我在代码中尝试实现的大纲:
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
我认为我基本上需要一个锁机制,但是在同一线程内?
pause
或resume
函数;如果线程正在阻塞等待条件,则没有其他任何操作。线程的run
函数是实际运行在指定线程中的唯一函数,另一个线程会暂停(等待工作线程真正处于空闲状态),并在稍后的某个时间点恢复执行。 - ShadowRangerresume
释放。但如果它没有暂停,所有线程都会打印,直到它被暂停。切换到notify_all
会让它们全部同时唤醒(这可能是最好的一致性)。如果你想让只有一个线程做某件事情,你需要采用不同的设计。 - ShadowRanger