if __name__ == "__main__": for i inrange(5): t = td.Thread(target=do_something, args=(i,)) t.start() # t.join() # 等待子线程结束,才执行主线程后面的语句,在for循环使用的话就变成了单线程
多进程
适用于计算密集型任务
基本使用
1 2 3
p = mp.Process(target=Job, args=(a,)) p.start() p.join()
锁、变量共享
1 2 3 4 5 6 7 8
lock = mp.Lock() lock.acquire() lock.release()
# 生成队列,放置值 queue = mp.Queue() # 各进程共享全局变量 value = mp.Value()
import multiprocessing as mp from concurrent.futures import ThreadPoolExecutor
defcalculate_job(ranNum): return [i + i**2 + i**3for i inrange(ranNum)]
if __name__ == "__main__": """ 完成1000次calculate_job(100) 所花时间 """
# exited with code=0 in 12.048 seconds for i inrange(1000): calculate_job(10000)
# exited with code=0 in 10.4 seconds num_lst = [10000for i inrange(1000)] pool = mp.Pool(processes=10) pool.map(calculate_job, num_lst)
# exited with code=0 in 12.391 seconds Pool = ThreadPoolExecutor(max_workers=10) num_lst = [10000for i inrange(1000)] for task in Pool.map(calculate_job, num_lst): pass