使用python线程执行多个模型运行,并可能更新队列
我正在多核windows机器上运行数值模拟。接下来,我能够用输入文件名列表填充队列,我使用这些文件名以文件名作为参数运行可执行文件 每次模拟运行都需要几个小时,我时不时地检查结果,并意识到我应该为一次或多次运行修改输入文件中的参数。现在,我想向同一队列添加新的文件名,而不必终止主程序。我正在考虑使用一个包含输入文件名的文本文件,这些文件名被读取并输入队列。因此,程序必须在每次线程完成任务时读取文本文件,并将已添加到列表末尾的文件名添加到队列中 这有可能吗?怎么可能?下面是我的代码:使用python线程执行多个模型运行,并可能更新队列,python,multithreading,Python,Multithreading,我正在多核windows机器上运行数值模拟。接下来,我能够用输入文件名列表填充队列,我使用这些文件名以文件名作为参数运行可执行文件 每次模拟运行都需要几个小时,我时不时地检查结果,并意识到我应该为一次或多次运行修改输入文件中的参数。现在,我想向同一队列添加新的文件名,而不必终止主程序。我正在考虑使用一个包含输入文件名的文本文件,这些文件名被读取并输入队列。因此,程序必须在每次线程完成任务时读取文本文件,并将已添加到列表末尾的文件名添加到队列中 这有可能吗?怎么可能?下面是我的代码: import
import os,subprocess,sys
import multiprocessing as mp
from queue import Queue
from threading import Thread
import threading
import shutil
def run(f,ws):
print('Running %s\n' % f)
ZSoil = r'c:\Program Files\ZSoil\ZSoil 2019 v19.03 x64\Z_Soil.exe '
subprocess.check_call('%s %s\\%s /E'%(ZSoil,ws,f))
def worker(queue):
"""Process files from the queue."""
for args in iter(queue.get, None):
try:
run(*args)
except Exception as e: # catch exceptions to avoid exiting the
# thread prematurely
print('%r failed: %s' % (args, e,), file=sys.stderr)
def main():
# populate files
ws = r'C:\Run2\model1'
q = Queue()
for ks in range(5):
for kc,c in enumerate(['Gmin','Gmed','Gmax']):
q.put_nowait(('Model_R2v1_%s_SET%i.inp'%(c,ks+1),ws))
# start threads
threads = [Thread(target=worker, args=(q,)) for _ in range(mp.cpu_count()-1)]
for t in threads:
t.daemon = True # threads die if the program dies
t.start()
for _ in threads: q.put_nowait(None) # signal no more files
for t in threads: t.join() # wait for completion
if __name__ == '__main__':
mp.freeze_support() # optional if the program is not frozen
main()