admin管理员组

文章数量:1565768

最近在使用python多线程的时候遇到了这个问题,将函数提交到线程中总是会报错RuntimeError: cannot schedule new futures after interpreter shutdown,这个问题主要是由于在子线程中调用了submit方法,例如如果在主线程中调用就不会出现上述问题。

例如,我的函数receive_response(self)函数是作为一个子线程开启的,所以一开始会报错

class Client:
    def init(self, args):
        # init 部分代码省略
        # 创建线程池来处理回复的消息
        selfmand_executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)  # 假设我们设置最大线程数为3
        # 创建线程来接收回复的消息
        self.receive_response_thread = threading.Thread(target=self.receive_response)
        self.receive_response_thread.start()

    def receive_response(self):
        # 部分代码省略
        while True:
            # ... 接收command操作
            selfmand_executor.submit(self.handle_command, command)
            # ... 其他操作

    def handle_command(self, command)
        pass
      

修正后的代码如下,我将receive_response设置为主线程(之前所有函数都是子线程,没有设置主线程),在主线程中使用submit函数,就能正常使用了,记得主线程需要用死循环包裹,不能停止。

class Client:
    def __init__(self, args):
        # 部分无关代码省略
        # 创建线程池来处理回复的消息
        selfmand_executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)  # 线程池大小

        # 创建线程来处理接收消息的任务(主线程)
        self.receive_response()  # 就是这边改了一下

    def receive_response(self):
        # 部分代码省略
        while True:
            # ... 接收command操作
            selfmand_executor.submit(self.handle_command, command)
            # ... 其他操作

    def handle_command(self, command)
        pass
      

本文标签: scheduleRuntimeErrorfuturesShutdowninterpreter