我正在做一个涉及数据收集和记录的项目。我有 2 个线程正在运行,一个收集线程和一个日志线程,都在 main 中启动。我试图让程序在使用 Ctrl-C 时优雅地终止。
我正在使用 athreading.Event
向线程发出信号以结束它们各自的循环。停止该sim_collectData
方法可以正常工作,但似乎没有正确停止logData
线程。Collection terminated
print 语句永远不会执行,程序只是停止。(它没有结束,只是坐在那里)。
第二个while
循环logData
是确保记录队列中的所有内容。目的是让 Ctrl-C 立即停止收集线程,然后让记录线程完成清空队列,然后才完全终止程序。(现在,数据只是被打印出来——最终它将被记录到数据库中)。
我不明白为什么第二个线程永远不会终止。我基于我所做的这个答案:在一定时间后停止线程。我错过了什么?
def sim_collectData(input_queue, stop_event):
''' this provides some output simulating the serial
data from the data logging hardware.
'''
n = 0
while not stop_event.is_set():
input_queue.put("DATA: <here are some random data> " + str(n))
stop_event.wait(random.randint(0,5))
n += 1
print "Terminating data collection..."
return
def logData(input_queue, stop_event):
n = 0
# we *don't* want to loop based on queue size because the queue could
# theoretically be empty while waiting on some data.
while not stop_event.is_set():
d = input_queue.get()
if d.startswith("DATA:"):
print d
input_queue.task_done()
n += 1
# if the stop event is recieved and the previous loop terminates,
# finish logging the rest of the items in the queue.
print "Collection terminated. Logging remaining data to database..."
while not input_queue.empty():
d = input_queue.get()
if d.startswith("DATA:"):
print d
input_queue.task_done()
n += 1
return
def main():
input_queue = Queue.Queue()
stop_event = threading.Event() # used to signal termination to the threads
print "Starting data collection thread...",
collection_thread = threading.Thread(target=sim_collectData, args=(input_queue, stop_event))
collection_thread.start()
print "Done."
print "Starting logging thread...",
logging_thread = threading.Thread(target=logData, args=(input_queue, stop_event))
logging_thread.start()
print "Done."
try:
while True:
time.sleep(10)
except (KeyboardInterrupt, SystemExit):
# stop data collection. Let the logging thread finish logging everything in the queue
stop_event.set()
main()