Python | threading05 - 使用有界信号量,实现线程间同步
生活随笔
收集整理的這篇文章主要介紹了
Python | threading05 - 使用有界信号量,实现线程间同步
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、前言
- 二、ValueError異常
- 2.1、測試有界信號量過多釋放是否真的會產生ValueError異常
- 三、生產者-消費者模型
- 3.1、代碼
- 3.2、運行的結果
一、前言
上一節學習完信號量,接著繼續學習有界信號量。
首先看看python官方對有界信號量的描述:
從官方的描述可以看到,release( )方法過多被調用時,就會產生ValueError異常。
二、ValueError異常
2.1、測試有界信號量過多釋放是否真的會產生ValueError異常
我在命令行測試了一下,過多的釋放的確會產生ValueError:Semaphore released too many times.
三、生產者-消費者模型
本次的代碼目的如下:
3.1、代碼
# python3.9 import time import threadingse1 = threading.BoundedSemaphore(2) # se1信號量的初始數量與上限值是2 se2 = threading.BoundedSemaphore(2) # se2信號量的初始數量與上限值是2# 消費者1線程函數 def customer1():global se1while True:print("customer1進入阻塞態,等待信號量的釋放。")se1.acquire() # 向se1信號量請求一個信號print("customer1請求信號量成功,time:%s" % time.perf_counter())# 消費者2線程函數 def customer2():global se2while True:print("customer2進入阻塞態,等待信號量的釋放。")se2.acquire() # 向se1信號量請求一個信號print("customer2請求信號量成功,time:%s" % time.perf_counter())# 生產者線程函數 def producer():while True:time.sleep(3) # 休眠3秒鐘# 釋放se1兩個信號se1.release()se1.release()# 釋放se2兩個信號se2.release()se2.release()print("producer釋放完信號量,其他線程將被同步。time:%s" % time.perf_counter())# 主線程函數t1 = threading.Thread(target=producer,name="thread_producer",daemon=True) # 創建producer子線程t2 = threading.Thread(target=customer1,name="thread_customer1",daemon=True) # 創建cusotmer1子線程t3 = threading.Thread(target=customer2,name="thread_customer2",daemon=True) # 創建customer2子線程t1.start() # 啟動producer線程 t2.start() # 啟動customer1線程t3.start() # 啟動customer2線程t1.join() # 子線程producer是無限循環的線程,所以主線程需要等待它運行結束t2.join() # 子線程customer1是無限循環的線程,所以主線程需要等待它運行結束t3.join() # 子線程customer2是無限循環的線程,所以主線程需要等待它運行結束print("主線程運行結束!")if __name__ == "__main__":main()3.2、運行的結果
跟上一節的運行結果一樣。
我個人認為,盡量避免使用信號量而是使用有界信號量,因為有界信號量的信號量被過多釋放時會出現警告ValueError。
總結
以上是生活随笔為你收集整理的Python | threading05 - 使用有界信号量,实现线程间同步的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python xlrd_python读取
- 下一篇: RTX5 | 软件定时器01 - 创建一