程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The fourth notes of 2022 Python winter vacation advanced training

編輯:Python
 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():

  • acquire(): Thread lock
  • release(): Release the lock
  • wait(timeout): Thread hanging , Until I get a notify Notification or timeout ( Optional , Floating point numbers , The unit is seconds s) Will be awakened and continue to run .wait() Must be obtained after Lock Only under the premise of , Otherwise it will trigger RuntimeError.
  • notify(n=1): Notify other threads , The suspended threads will start running after receiving this notification , The default is to notify a person who is waiting for the condition The thread of , Wake up at most n Waiting threads .notify() Must be obtained after Lock Only under the premise of , Otherwise it will trigger RuntimeError.notify() Will not actively release Lock.
  • notifyAll(): If wait More state threads ,notifyAll The role of the is to inform all threads
''' 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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved