繁体   English   中英

在实现Python的多处理时,函数会提供不同的返回值吗?

[英]When implementing Python's multiprocessing, function gives different return values?

当我从一个进程运行它与使用多处理调用它时,一个函数给出的结果不同。 我不知道为什么。 我正在从管理器创建一个列表,并为每个进程调用具有不同参数的相同目标函数。 目标函数调用从其他模块导入的函数。 基于导入的函数,根据我从多个进程或一个进程调用它的时间,它会给我带来不同的结果。

例如:

from foo import foo_function
from multiprocessing import Process, Manager


def another_function(indices, a_list, return_list):
    for i in indices:
        for j in a_list:
            return_list.append(foo_function(i, j))


if __name__ == '__main__':
    jobs = []
    manager = Manager()
    return_list = manager.list()
    all_indices = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
    all_lists = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
    for i in range(3):
        jobs.append(Process(target=another_function, args=(all_indices[i], all_lists[i])))
        jobs[i].start()
    for i in range(3):
        jobs[i].join()

当我从多个进程调用它时,与从一个进程调用它时,foo_function()给我不同的结果。

编辑:这是实际的foo_function是:

def battle(ally: CustomClass, enemy: CustomClass, shields: int):
    ally.starting_shields = shields
    enemy.starting_shields = shields

    ally.reset()
    enemy.reset()

    turns = 0

    # Main Battle Loop
    while ally.is_alive() and enemy.is_alive():
        ally.reduce_cooldown()
        enemy.reduce_cooldown()

        turns += 1
        if ally.can_act():
            if not ally.use_charge_move(enemy):
                ally.use_move(ally.fast_move, enemy)

        if enemy.can_act():
            if not enemy.use_charge_move(ally):
                enemy.use_move(enemy.fast_move, ally)

    # There are 2 points for using enemy shields and 3 for using enemy health.
    ally_rating = enemy.starting_shields - enemy.get_shields()
    enemy_rating = ally.starting_shields - ally.get_shields()
    ally_rating += 5 * (enemy.starting_health - enemy.get_health()) / enemy.starting_health
    enemy_rating += 5 * (ally.starting_health - ally.get_health()) / ally.starting_health
    if ally.get_health() > 0:
        ally_rating += 3 * ally.energy / 100
    if enemy.get_health() > 0:
        enemy_rating += 3 * enemy.energy / 100

    total_rating = ally_rating + enemy_rating
    return int(round(1000 * ally_rating / total_rating, 0)), int(round(1000 * enemy_rating / total_rating, 0))

如您所见,它仅调用CustomClasses方法,并且仅使用局部变量。

不知道foo_function很难说,但这可能是由于不同的进程访问了对同一列表的引用并发现每个列表具有不同的值,因为那里似乎没有任何并发​​处理。

该问题最终成为与多处理无关的问题。 抱歉。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM