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…
互斥锁-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…