37 signal amount, conditions

Semaphore (Semaphore) controlled only by access code n threads

import time
from threading import Semaphore,Thread
def func(sem,a , b):
    sem.acquire()
    time.sleep(1)
    print(a+b)
    sem.release()
sem=Semaphore(4)
for i in range(10):
    t = Thread(target=func,args=(sem,i,i+5))
    t.start()

Output:
Here Insert Picture Description

condition

from threading import Condition
from threading import Thread
'''
条件,更复杂的锁
不仅提供acquire() release() 还提供wait() notify()
一个条件被创建之处,默认有一个False状态,false状态影响wait(),让wait一直处于等待状态
notify(int数据类型) 制造int把钥匙
'''

def func(c,i):
    c.acquire()
    c.wait()
    print('在第%s个循环里'%i)
    c.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()

queue

queue

import queue

q = queue.Queue()  # 队列 先进先出
q.put()
q.get()
q.put_nowait()
q.get_nowait()

Stack

import queue
q = queue.LifoQueue()  # 栈 先进后出
q.put(1)
q.put(2)
q.put(3)
print(q.get())
print(q.get())

Priority queue

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())

Guess you like

Origin blog.csdn.net/weixin_43265998/article/details/91822254
37