Python中有多種方式可以實現并行處理,以下是一些常用的方法:
import threading
def task():
# 任務代碼
threads = []
for i in range(10):
t = threading.Thread(target=task)
threads.append(t)
t.start()
for t in threads:
t.join()
from multiprocessing import Process
def task():
# 任務代碼
processes = []
for i in range(10):
p = Process(target=task)
processes.append(p)
p.start()
for p in processes:
p.join()
from concurrent.futures import ThreadPoolExecutor
def task():
# 任務代碼
with ThreadPoolExecutor() as executor:
results = [executor.submit(task) for _ in range(10)]
for result in results:
result.result()
以上是一些常用的并行處理方法,可以根據具體需求選擇合適的方法來實現并行處理。