抱歉这个老问题。我澄清了。如何用我糟糕的线程类启动一个停止线程?
编辑:它处于循环中,我想在代码的开头再次重启它。我怎么做start-stop-restart-stop-restart?
我的课程:
import threading
class Concur(threading.Thread):
def __init__(self):
self.stopped = False
threading.Thread.__init__(self)
def run(self):
i = 0
while not self.stopped:
time.sleep(1)
i = i + 1
在主要代码中,我想:
inst = Concur()
while conditon:
inst.start()
#after some operation
inst.stop()
#some other operation
答案 0 :(得分:15)
您实际上无法停止然后重新启动线程,因为在start()
方法终止后无法再次调用run()
。但是,您可以通过使用threading.Condition
变量使一个停止并稍后恢复执行,以避免在检查或更改其运行状态时出现并发问题。
Condition
个对象具有关联的threading.Lock
对象和方法,等待它被释放,并在发生时通知任何等待的线程。这是一个从您的问题中的代码派生的示例,它显示了这一点。在示例代码中,我将Condition
变量作为Thread
子类实例的一部分,以更好地封装实现,并避免需要引入其他全局变量:
from __future__ import print_function
import threading
import time
class Concur(threading.Thread):
def __init__(self):
super(Concur, self).__init__()
self.iterations = 0
self.daemon = True # Allow main to exit even if still running.
self.paused = True # Start out paused.
self.state = threading.Condition()
def run(self):
self.resume()
while True:
with self.state:
if self.paused:
self.state.wait() # Block execution until notified.
# Do stuff.
time.sleep(.1)
self.iterations += 1
def resume(self):
with self.state:
self.paused = False
self.state.notify() # Unblock self if waiting.
def pause(self):
with self.state:
self.paused = True # Block self.
class Stopwatch(object):
""" Simple class to measure elapsed times. """
def start(self):
""" Establish reference point for elapsed time measurements. """
self.start_time = time.time()
return self.start_time
@property
def elapsed_time(self):
""" Seconds since started. """
try:
start_time = self.start_time
except AttributeError: # Wasn't explicitly started.
start_time = self.start()
return time.time() - start_time
MAX_RUN_TIME = 5 # Seconds.
concur = Concur()
stopwatch = Stopwatch()
print('Running for {} seconds...'.format(MAX_RUN_TIME))
concur.start()
while stopwatch.elapsed_time < MAX_RUN_TIME:
concur.resume()
# ... do some concurrent operations.
concur.pause()
# Do some other stuff...
# Show Concur thread executed.
print('concur.iterations: {}'.format(concur.iterations))
答案 1 :(得分:7)
这是David Heffernan的想法充实。下面的示例运行1秒钟,然后停止1秒钟,然后运行1秒钟,依此类推。
import time
import threading
import datetime as DT
import logging
logger = logging.getLogger(__name__)
def worker(cond):
i = 0
while True:
with cond:
cond.wait()
logger.info(i)
time.sleep(0.01)
i += 1
logging.basicConfig(level=logging.DEBUG,
format='[%(asctime)s %(threadName)s] %(message)s',
datefmt='%H:%M:%S')
cond = threading.Condition()
t = threading.Thread(target=worker, args=(cond, ))
t.daemon = True
t.start()
start = DT.datetime.now()
while True:
now = DT.datetime.now()
if (now-start).total_seconds() > 60: break
if now.second % 2:
with cond:
cond.notify()
答案 2 :(得分:4)
stop()
的实现如下所示:
def stop(self):
self.stopped = True
如果要重新启动,则可以创建一个新实例并启动它。
while conditon:
inst = Concur()
inst.start()
#after some operation
inst.stop()
#some other operation
Thread
的{{3}}表明start()
方法只能为每个类的实例调用一次。
如果您想暂停和恢复某个帖子,那么您需要使用documentation。