1

我正在使用 multiprocessing.Pool 来并行化我为模拟(D&D 5e 中的战斗)编写的一些 Python 代码。但是,我收到此错误:can't pickle _thread.RLock objects. 我做了一些研究,看起来问题是我的模拟使用了具有记录器的对象(来自logging模块)。我仍然希望支持对模拟的单进程运行进行日志记录(以便人们可以进行调试/检查输出),但是对多进程运行的日志支持对我来说不太重要,因为一旦用户知道模拟正常工作,他们一般不需要逐个播放。我怎样才能重构我的代码,使日志记录在这里不是问题(当有多个进程时禁用日志记录,以多处理接受的方式实现日志记录,或其他)?

我的模拟课程中的一些代码:

    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))

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

4

0 回答 0