gpt4 book ai didi

python - 如何防止 python 中的并行 for 循环访问同一个文件夹两次?

转载 作者:行者123 更新时间:2023-11-28 22:30:00 24 4
gpt4 key购买 nike

我正在编写一个 python 程序,该程序并行运行外部模型一定次数,以在参数空间中定义数据。由于外部模型的编写方式(我保证有充分的理由),如果我想同时运行它,我必须为模型文件夹制作一个新副本。我制作了主模型文件夹 foo 的副本,并将它们命名为 foo0、foo1、foo2 和 foo3。现在我希望能够进入基于线程的特定目录,进行一些更改,运行模型,写入主文件,然后移动到下一个运行。每个模型运行可能需要 30 到 200 秒,因此并行运行与串行运行相比具有优势。

import subprocess
from joblib import Parallel

def run_model(base_path):
#Make some changes using a random number generator in the folder
....
#Run the model using bash on windows. Note the str(threading.get_ident()) is my
#attempt to get the thread 0,1,2,3
subprocess.run(['bash','-c', base_path + str(threading.get_ident()) + '/Model.exe'])
#Write some input for the run to a main file that will store all runs
with open('Inputs.txt','a') as file:
with open(base_path + str(threading.get_ident()) + '/inp.txt') as inp_file:
for i,line in enumerate(inp_file):
if i == 5:
file.write(line)

Parallel(n_jobs=4, backend="threading")(run_model('Models/foo') for i in range(0,10000))

但是,由于线程 ID 不断变化且文件夹不存在,我不断收到 FileNotFoundError。该模型很大,因此使用新线程 ID(类似于名为 foo+thread_id 的文件夹)复制模型既慢又占用大量磁盘空间。有什么方法可以限制模型的某个副本仅在某个线程上运行,以确保它不被任何其他线程使用?

最佳答案

你可以像这样构造你的程序:

  1. 首先,主线程搜索需要处理的文件夹,并将它们放入一个线程安全的队列中。在此阶段,您确保队列仅包含唯一项目。在队列周围使用同步原语,以确保一次只有一件事访问它。
  2. 工作线程已启动
  3. 工作线程从同步的线程安全队列中取出工作,并处理它们。
  4. 当队列中没有剩余工作时线程加入
  5. 当所有线程都加入后,工作就完成了。

图片是这样的:

   Queue of unique dirs is constructed.
||
\/ Consumer 0
/
/ /Consumer 1
Queue(DirD->DirC->DirB->DirA) ...
\ \Consumer i
|| \ ...
\/ Consumer n

Dirs are processed.

关于python - 如何防止 python 中的并行 for 循环访问同一个文件夹两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42706582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com