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

标签 multithreading python-3.x python-multithreading

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

   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() 循环内的 bool 变量 - 在这里不起作用。处理这个问题的推荐方法是什么?

我可以只设置 Daemon 标志,但随后我将无法使用 quit() 方法,这可能在以后证明很有值(value)(进行一些清理)。有任何想法吗?

最佳答案

AFAIK,Python 3 中没有内置机制(就像在 Python 2 中一样)。您是否尝试过使用 PyThreadState_SetAsyncExc 行之有效的 Python 2 方法? , 记录 herehere ,或替代跟踪方法 here ?
这是 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)

关于multithreading - 如何在读取流时正确终止 Python3 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5899692/

相关文章:

python - 为什么我的线程在启动之前就执行目标函数?

python - 使用 __stop 停止的线程不会从 threading.enumerate() 中删除

c++ - 在 QueueUserAPC 中指定的回调未被调用

multithreading - 研究 XMPP 应用程序的线程实现的好资源是什么?

python - 如何打印按点数排序? Python

python-3.x - 使用 Python 创建新的 Access 数据库和表

html - 如何从类内的微数据元标记中检索内容值

java - ThreadPool 中的 Runnable 与线程内和 ThreadPool 中的 Runnable 之间有什么区别

c# - 多线程单元测试

python-2.7 - 在python qt中带有线程的Qwebview