如何在读取流时正确终止Python3线程

abw*_*abw 5 multithreading python-multithreading python-3.x

我正在使用一个线程从流(/ dev/tty1)读取字符串,同时处理主循环中的其他内容.我想在按CTRL-C时Thread与主程序一起终止.

   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 Code Online (Sandbox Code Playgroud)

通常的解决方案 - run()循环中的布尔变量 - 在这里不起作用.推荐的解决方法是什么?

我可以设置守护进程标志,但之后我将无法使用quit()方法,这可能在以后证明是有价值的(做一些清理).有任何想法吗?

Irf*_*rfy 6

AFAIK,Python 3 中没有内置机制(就像在 Python 2 中一样)。您是否尝试过与成熟的Python 2的方式PyThreadState_SetAsyncExc,记录在这里和这里,或替代办法跟踪这里?

这是PyThreadState_SetAsyncExc上面方法的稍微修改版本:

import threading
import inspect
import ctypes 
 
def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble, 
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")
 
def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)
Run Code Online (Sandbox Code Playgroud)