python基础一 day40 条件 定时器 队列 线程池
# 条件
# 锁
# acquire release
# 一个条件被创建之初 默认有一个False状态
# False状态 会影响wait一直处于等待状态
# notify(int数据类型) 造钥匙
notify和wait需要在acquire release之间
wait()是在等钥匙,写在acquire和wait之间的代码不受钥匙限制,要锁的代码必须放在wait后面
造出来的钥匙是不会还的,只能用一次
from threading import Thread,Condition def func(con,i): con.acquire() con.wait() # 等钥匙 print('在第%s个循环里'%i) con.release() con = Condition() for i in range(10): Thread(target=func,args = (con,i)).start() while True: num = int(input('>>>')) con.acquire() con.notify(num) # 造钥匙 con.release()
定时器
import time from threading import Timer def func(): print('时间同步') #1-3 while True: t = Timer(5,func).start() # 非阻塞的 time.sleep(5)
队列:
# queue import queue q = queue.Queue() # 队列 先进先出 # q.put() # q.get() # q.put_nowait() # q.get_nowait() # q = queue.LifoQueue() # 栈 先进后出 # q.put(1) # q.put(2) # q.put(3) # print(q.get()) # print(q.get()) q = queue.PriorityQueue() # 优先级队列 q.put((20,'a')) q.put((10,'b')) q.put((30,'c')) q.put((-5,'d')) q.put((1,'?')) print(q.get())
线程池:
import time from concurrent.futures import ThreadPoolExecutor def func(n): time.sleep(2) print(n) return n*n def call_back(m): print('结果是 %s'%m.result()) tpool = ThreadPoolExecutor(max_workers=5) # 默认 不要超过cpu个数*5 for i in range(20): tpool.submit(func,i).add_done_callback(call_back) # tpool.map(func,range(20)) # 拿不到返回值 # t_lst = [] # for i in range(20): # t = tpool.submit(func,i) # t_lst.append(t) # tpool.shutdown() # close+join # # print('主线程') # for t in t_lst:print('***',t.result()) # ftp # 并发编程