from concurrent.futures import ThreadPoolExecutor import time def func(n): time.sleep(2) print(n) return n*n t_pool = ThreadPoolExecutor(max_workers=20) #max_workers一般不超过CPU*5,创建线程池 t_lst = [] for i in range(20): t = t_pool.submit(func,i) #提交多线程认为 t_…
from threading import Thread import time def func(n): #子线程完成的 time.sleep(1) print(n) #多线程示例 for i in range(10): t = Thread(target=func, args=(i,)) #func的子线程注册到主线程 t.start() 使用面向对象的方式开启新的线程 from threading import Thread import time class MyThread(Threa…
并发是快速处理大量相似任务的绝佳办法,但对于有返回值的方法,需要一个容器专门来存储每个进程处理完的结果 from multiprocessing import Pool import time #返回值只有进程池才有,父子进程没有返回值 def func(i): time.sleep(1) return i*i if __name__ == '__main__': p = Pool(5) #从异步提交任务获取结果 res_l = [] for i in range(20): res = p.ap…
互斥锁-Lock #多线程中虽然有GIL,但是还是有可能产生数据不安全,故还需加锁 from threading import Lock, Thread #互斥锁 import time def eat1(lock): global n lock.acquire() temp =n time.sleep(0.2) n = temp - 1 lock.release() if __name__ == '__main__': n = 10 t_lst = [] lock = Lock() for i…