【发布时间】:2015-11-10 21:49:36
【问题描述】:
我正在尝试创建一个线程,它在后台执行操作。我需要能够在需要时有效地“暂停”它,并在以后再次“恢复”它。此外,如果当我“暂停”它时线程正在做某事,它应该让调用线程等待,直到它完成它正在做的事情。
我对 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
我想我基本上需要一个锁定机制,但在同一个线程中?
【问题讨论】:
标签: python multithreading