使用日志记录时,Python多处理“无法腌制”

我正在使用multiprocessing.Pool来并行化我为仿真而编写的某些Python代码(在D&D 5e中进行战斗)。但是,我收到此错误:can't pickle _thread.RLock objects。我做了一些研究,看来问题是我的仿真使用了具有记录器的对象(来自logging模块)。我仍然想支持模拟的单进程运行的日志记录(以便人们可以调试/检查输出),但是对多进程运行的日志记录支持对我而言并不重要,因为一旦用户知道模拟正确运行,他们就可以通常不需要逐个播放。我该如何重构代码,以使日志记录不再成为问题(在有多个进程的情况下禁用日志记录,以多进程接受的方式实现日志记录,或者其他方式)?

我的Simulation类中的一些代码:

    def process_run(self,num):  # pylint: disable=unused-argument
        """
        The method given to an individual process to do work. Run only once per process so we don't need to reset anything

        :param num: which iteration of the loop am I
        :return:
        """
        self._encounter.run()
        return self._encounter.get_stats()

    def mp_run(self,n=1000,p=None):
        """
        Run the Encounter n times (using multiprocessing),then print the results
        :param n: number of times to run the encounter
        :param p: number of processes to use. If None,use max number of processes
        :return: aggregate stats
        """
        if p:
            pool = Pool(p)  # use user-specified number of processes
        else:
            pool = Pool()  # use max number of processes as user didn't specify
        for result in pool.imap_unordered(self.process_run,range(n)):
            self.update_stats(result)
        pool.close()
        pool.join()
        self.calculate_aggregate_stats(n)
        self.print_aggregate_stats()
        return self._aggregate_stats

一些使用日志记录的代码(来自Encounter类,每个Simulation都有一个实例):

            self.get_logger().info("Round %d",self.get_round())
            unconscious = [comb.get_name() for comb in self.get_combatants() if comb.has_condition("unconscious")]
            if unconscious:
                self.get_logger().info("Unconscious: %s",str(unconscious))
            dead = [comb.get_name() for comb in self.get_combatants() if comb.has_condition("dead")]
            if dead:
                self.get_logger().info("Dead: %s",str(dead))

如果您需要更多代码示例,请告诉我。

qq8023tt 回答:使用日志记录时,Python多处理“无法腌制”

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3142751.html

大家都在问