One 、 Semaphore : A piece of code can only be n Process execution Example : # Semaphore : Control concurrency import threading import time def run(n): semaphore.acquire() # Start event volume print(n) time.sleep(1) semaphore.release()# Release event volume if __name__ == '__main__': semaphore = threading.Semaphore(5)# Run five threads at a time , One of the threads ends the lock release for i in range(50): t = threading.Thread(target=run,args=(i,)) t.start()
Two 、Condition( Condition variables, ) Usually associated with a lock . Need more than one Contidion When sharing a lock in , You can pass a Lock/RLock Examples to construct methods , Otherwise it will generate a RLock example .
It can be said that , except Lock With the lock out of the pool ,Condition It also contains a waiting pool , The threads in the pool are in the waiting blocking state in the state diagram , Until another thread calls notify()/notifyAll() notice ; When notified, the thread enters the lock pool and waits for the lock .
Condition():
''' Condition variables, ''' import threading import time def run(x): con.acquire() print(f' Threads {x}') con.notify() # Tell the next thread wait end print(f' Threads {x} Hang up ') con.wait() time.sleep print(f' Threads {x} Start again ') con.notify() con.release() if __name__ == '__main__': con = threading.Lock() # Instantiate condition variables # for i in range(10): t = threading.Thread(target=run,args=(1,)) t.start() Example : Implementation scenario : When a Classmate Wang hot pot is filled with fish balls ( most 5 individual , Notify when full b Eat it ), notice b Students eat fish balls ( Eat to 0 Notice when a Students continue to add )
# coding=utf-8 import threading import time con = threading.Condition() num = 0 # producer class Producer(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): # Lock thread global num con.acquire() while True: print " Start adding !!!" num += 1 print " The number of fish balls in the hot pot :%s" % str(num) time.sleep(1) if num >= 5: print " The number of fish balls in the hot pot has reached 5 individual , Unable to add !" # Wakes up the waiting thread con.notify() # Wake up the little friend and eat # Wait for a notice con.wait() # Release the lock con.release() # consumer class Consumers(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): con.acquire() global num while True: print " Start eating !!!" num -= 1 print " The number of fish balls left in the hot pot :%s" %str(num) time.sleep(2) if num <= 0: print " The bottom of the pot is out of stock , Add fish balls quickly !" con.notify() # Wake up other threads # Wait for a notice con.wait() con.release() p = Producer() c = Consumers() p.start() c.start()
3、 ... and 、 event
(1) A single signal can put all processes into a blocking state
(2) You can also control all processes to unblock
(3) After an event is created , The default is blocking
Example :
import threading import time def car(): while True: if event.is_set(): # If the event is executing print(' The car runs ') else: print(' The trolley stops ') event.wait() # Events wait def set_event(): while True: event.set() # Start events time.sleep(1) event.clear() # Clear the event time.sleep(1) if __name__ == '__main__': event = threading.Event() # Create an event car1 = threading.Thread(target=car) car1.start() set_e = threading.Thread(target=set_event) set_e.start()
Video Explanation :https://space.bilibili.com/196858266/channel/collectiondetail?sid=57996
Condition() Condition variables, :
Official documents :threading --- Thread based parallelism — Python 3.9.9 file