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())
這兩種方法都可以實現多進程并發執行任務,具體使用哪種方法取決于具體的需求和場景。