Python 具有固定资源的多处理

Python 具有固定资源的多处理,python,python-3.x,multiprocessing,python-multiprocessing,Python,Python 3.x,Multiprocessing,Python Multiprocessing,我有10个任务和4个资源。每个任务都需要一个资源来运行和完成,因此一次最多可以并行运行4个任务。如果使用了所有资源,则新任务只能在释放现有资源时启动,并且在使用该资源的任务完成时才会启动。无论何时任何进程中发生错误,都要停止多处理池。下面是代码。看起来它正在工作,但是对于我上面提到的规范,这是最简单/正确的方法吗 def init_mapping(i,resource_mapping): resource_mapping[os.getpid()] = i def run_task(i,

我有10个任务和4个资源。每个任务都需要一个资源来运行和完成,因此一次最多可以并行运行4个任务。如果使用了所有资源,则新任务只能在释放现有资源时启动,并且在使用该资源的任务完成时才会启动。无论何时任何进程中发生错误,都要停止多处理池。下面是代码。看起来它正在工作,但是对于我上面提到的规范,这是最简单/正确的方法吗

def init_mapping(i,resource_mapping):
    resource_mapping[os.getpid()] = i

def run_task(i,resource_mapping,execution_list):
    s="execute task {} with resource {}".format(i,resource_mapping[os.getpid()])
    execution_list.append(s)

num_resources = 4
num_tasks=10

with multiprocessing.Pool(processes=num_resources) as pool:

    manager = multiprocessing.Manager()
    resource_mapping = manager.dict()
    execution_list = manager.list()

    init=[pool.apply_async(init_mapping, args = (i, resource_mapping)) for i in range(num_resources)]

    time.sleep(1)

    run=[pool.apply_async(run_task, args=(i, resource_mapping, execution_list)) for i in range(num_tasks)]

    try:
        for result in init+run:
            result.get()
    except Exception as e:
        print("an error occur, halt the operation")
        raise e

print(execution_list)
print(resource_mapping)
输出:

['execute task 2 with resource 2', 'execute task 0 with resource 0', 'execute task 1 with resource 1', 'execute task 3 with resource 3', 'execute task 4 with resource 0', 'execute task 5 with resource 1', 'execute task 6 with resource 2', 'execute task 7 with resource 3', 'execute task 8 with resource 0', 'execute task 9 with resource 1']
{17771: 0, 17772: 1, 17773: 2, 17774: 3}