我认为Semaphore是您正在寻找的东西,它将在递减为0时阻止主进程。示例代码:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
time.sleep(5)
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
sema.acquire()
p = Process(target=f, args=(i, sema))
all_processes.append(p)
p.start()
for p in all_processes:
p.join()
由于以下代码sema
在同一函数中获取和释放,因此其结构更加结构化。但是,如果total_task_num
非常大,它将消耗太多资源:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
sema.acquire()
time.sleep(5)
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
p = Process(target=f, args=(i, sema))
all_processes.append(p)
p.start()
for p in all_processes:
p.join()
上面的代码将创建total_task_num
进程,但是只有concurrency
进程将运行,而其他进程被阻止,这将消耗宝贵的系统资源。