Python多进程实现的方法有两种:使用multiprocessing模块和使用concurrent.futures模块。
import multiprocessing
def worker(num):
print(f'Worker {num}')
if __name__ == '__main__':
processes = []
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
processes.append(p)
p.start()
for p in processes:
p.join()
import concurrent.futures
def worker(num):
return f'Worker {num}'
if __name__ == '__main__':
with concurrent.futures.ProcessPoolExecutor() as executor:
results = [executor.submit(worker, i) for i in range(5)]
for result in concurrent.futures.as_completed(results):
print(result.result())
这两种方法都可以实现多进程并发执行任务,具体使用哪种方法取决于具体的需求和场景。