1 回答

TA贡献1784条经验 获得超7个赞
我想通了。其实很简单。我们需要做的就是使用 amultiprocessing.Queue来管理可用的 GPU ID。通过初始化开始Queue到含有2每个GPU ID的,然后get从所述GPU IDqueue之初foo和put回末。
from multiprocessing import Pool, current_process, Queue
NUM_GPUS = 4
PROC_PER_GPU = 2
queue = Queue()
def foo(filename):
gpu_id = queue.get()
try:
# run processing on GPU <gpu_id>
ident = current_process().ident
print('{}: starting process on GPU {}'.format(ident, gpu_id))
# ... process filename
print('{}: finished'.format(ident))
finally:
queue.put(gpu_id)
# initialize the queue with the GPU ids
for gpu_ids in range(NUM_GPUS):
for _ in range(PROC_PER_GPU):
queue.put(gpu_ids)
pool = Pool(processes=PROC_PER_GPU * NUM_GPUS)
files = ['file{}.xyz'.format(x) for x in range(1000)]
for _ in pool.imap_unordered(foo, files):
pass
pool.close()
pool.join()
添加回答
举报