Python | threading04 - 使用信号量,实现线程间同步
生活随笔
收集整理的這篇文章主要介紹了
Python | threading04 - 使用信号量,实现线程间同步
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、前言
- 二、生產者-消費者模型
- 2.1、代碼
- 2.2、運行的結果
- 2.3、Semaphore沒有設置上限值
一、前言
先說一下信號量與互斥量之間的關系。信號量的一個特殊的應用是互斥鎖(互斥量),當信號量的最大數量是1時,它跟互斥鎖(互斥量)的作用相同。
以下摘自《python并行編程》中文版:
二、生產者-消費者模型
本次的代碼目的如下:
2.1、代碼
# python3.9 import time import threadingse1 = threading.Semaphore(0) # se1信號量的初始數量是0 se2 = threading.Semaphore(0) # se2信號量的初始數量是0# 消費者1線程函數 def customer1():global se1while True:# print("customer1請求se1信號量。")se1.acquire() # 向se1信號量請求一個信號print("customer1請求信號量成功,time:%s" % time.perf_counter())# 消費者2線程函數 def customer2():global se2while True:# print("customer2請求se2信號量。")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())# 主線程函數 def main():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()2.2、運行的結果
python多線程的信號量跟單片機RTOS的信號量真的很相似。如果之前接觸過RTOS的信號量的話,python的信號量也很快可以掌握。
2.3、Semaphore沒有設置上限值
在代碼中,只設置了信號量的初始值。
因為我將信號量的初始值設為0,所以線程customer1與線程customer2在剛被創建的時候就進入了阻塞態(因為沒有信號量)。
Semaphore沒有設置上限值,所以可能會出現信號量釋放的次數過多(多于本來規劃的值)。為了避免這個情況的出現,Python的多線程還有另外一個工具叫做有界信號量。
單片機的RTOS上的信號量跟python的有界信號量一樣,能防止信號量釋放的次數過多。
總結
以上是生活随笔為你收集整理的Python | threading04 - 使用信号量,实现线程间同步的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html语言table,html中的ta
- 下一篇: ubuntu18.04安装python3