我正在使用線程在處理主循環中的其他內容時從流(/ dev/tty1)讀取字符串。我希望線程在按CTRL-C時與主程序一起終止。如何在讀取流時正確終止Python3線程
from threading import Thread
class myReader(Thread):
def run(self):
with open('/dev/tty1', encoding='ascii') as myStream:
for myString in myStream:
print(myString)
def quit(self):
pass # stop reading, close stream, terminate the thread
myReader = Reader()
myReader.start()
while(True):
try:
pass # do lots of stuff
KeyboardInterrupt:
myReader.quit()
raise
通常的解決方案 - run()循環內的布爾變量 - 在這裏不起作用。建議如何處理這個問題?
我可以只設置守護程序標誌,但後來我將無法使用quit()方法,這在以後可能證明有價值(做一些清理)。有任何想法嗎?
我發現我需要'ctypes.c_long(tid)',否則我會得到'res == 0' – faulty 2014-10-15 03:22:40