039條件變數同步(Condition)

来源:https://www.cnblogs.com/-nbloser/archive/2018/03/10/8539286.html
-Advertisement-
Play Games

也是鎖,這個鎖多加了wait(),notify()喚醒一個進程,notifyall()喚醒全部進程方法,創建的時候預設是Rlock類型的鎖,可以設置為lock類型的,預設就ok 1 from random import randint 2 import threading 3 import time ...


也是鎖,這個鎖多加了wait(),notify()喚醒一個進程,notifyall()喚醒全部進程方法,創建的時候預設是Rlock類型的鎖,可以設置為lock類型的,預設就ok

 1 from random import randint
 2 import threading
 3 import time
 4 
 5 class Producer(threading.Thread):
 6     def run(self):
 7         global L
 8         while True:
 9             val = randint(0,100)
10             print('生產者',self.name,':append',str(val),L)
11             if lock_con.acquire():
12                 L.append(val)
13                 lock_con.notify()
14                 lock_con.release()
15             time.sleep(3)
16 
17 class Consumer(threading.Thread):
18     def run(self):
19         global  L
20         while True:
21             lock_con.acquire()
22             if len(L) == 0:
23                 lock_con.wait()
24             print('消費者',self.name,'delete',str(L[0]),L)
25             del L[0]
26             lock_con.release()
27         time.sleep(0.5)
28 
29 if __name__ == '__main__':
30     L = []
31     lock_con = threading.Condition()
32     threads = []
33     for i in range(5):
34         threads.append(Producer())
35         threads.append(Consumer())
36     for t in threads:
37         t.start()
38     for t in threads:
39         t.join()
使用例子

 

###########java改編:單生產單消費

 1 import time
 2 import threading
 3 
 4 class Res:
 5     def __init__(self):
 6         self.flag = False
 7         self.count = 0
 8         self.product = ''
 9 
10     def set(self,name):
11         lock_con.acquire()
12         if self.flag:
13             lock_con.wait()
14         time.sleep(0.00001)
15         self.count += 1
16         self.product = ''.join([name,'**',str(self.count)])
17         self.message = ''.join([self.product,'__生產者__',str(threading.current_thread())])
18         print(self.message)
19         self.flag = True
20         lock_con.notify()
21         lock_con.release()
22 
23     def get_product(self):
24         lock_con.acquire()
25         time.sleep(0.00001)
26         if not self.flag:
27             lock_con.wait()
28         self.message = ''.join([self.product,'__消費者__',str(threading.current_thread())])
29         print(self.message)
30         self.flag = False
31         lock_con.notify()
32         lock_con.release()
33 
34 class Producer(threading.Thread):
35     def __init__(self,r):
36         threading.Thread.__init__(self)
37         self.r = r
38 
39     def run(self):
40         for i in range(100):
41             self.r.set('大白兔奶糖')
42 
43 class Consumer(threading.Thread):
44     def __init__(self,r):
45         threading.Thread.__init__(self)
46         self.r = r
47 
48     def run(self):
49         for i in range(100):
50             self.r.get_product()
51 
52 if __name__ == '__main__':
53     lock_con = threading.Condition()
54     r = Res()
55     c = Consumer(r)
56     p = Producer(r)
57     c.start()
58     p.start()
單生產單消費

 

############多生產多消費

 1 import time
 2 import threading
 3 
 4 class Res:
 5     def __init__(self):
 6         self.flag = False
 7         self.count = 0
 8         self.product = ''
 9 
10     def set(self,name):
11         lock_con.acquire()
12         while self.flag:
13             lock_con.wait()
14         time.sleep(0.00001)
15         self.count += 1
16         self.product = ''.join([name,'**',str(self.count)])
17         self.message = ''.join([self.product,'__生產者__',str(threading.current_thread())])
18         print(self.message)
19         self.flag = True
20         lock_con.notifyAll()
21         lock_con.release()
22 
23     def get_product(self):
24         lock_con.acquire()
25         time.sleep(0.00001)
26         while not self.flag:
27             lock_con.wait()
28         self.message = ''.join([self.product,'__消費者__',str(threading.current_thread())])
29         print(self.message)
30         self.flag = False
31         lock_con.notifyAll()
32         lock_con.release()
33 
34 class Producer(threading.Thread):
35     def __init__(self,r):
36         threading.Thread.__init__(self)
37         self.r = r
38 
39     def run(self):
40         for i in range(100):
41             self.r.set('大白兔奶糖')
42 
43 class Consumer(threading.Thread):
44     def __init__(self,r):
45         threading.Thread.__init__(self)
46         self.r = r
47 
48     def run(self):
49         for i in range(100):
50             self.r.get_product()
51 
52 if __name__ == '__main__':
53     lock_con = threading.Condition()
54     r = Res()
55     l = []
56     for i in range(5):
57         l.append(Consumer(r))
58     for i in range(5):
59         l.append(Producer(r))
60     for a in l:
61         a.start()
多生產多消費

 

個人覺得例子理解是最好的,所以我學的東西一般使用例子


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1、@Controller 在SpringMVC 中,控制器Controller 負責處理由DispatcherServlet 分發的請求,它把用戶請求的數據經過業務處理層處理之後封裝成一個Model ,然後再把該Model 返回給對應的View 進行展示。在SpringMVC 中提供了一個非常簡便 ...
  • 查找最大的N個元素——堆數據結構 給出序列,求出TopK大的元素,使用小頂堆,heapq模塊實現 ...
  • 第一種:點對點 第二種: 發佈者/訂閱者 啟動順序:先訂閱、再發佈 ...
  • 函數:就是讓程式模塊化,把具有獨立功能的代碼塊當成一個整體封裝成一個函數 首先列印一個佛主看看: 那麼這個時候我們想列印很多遍佛主的話,總不能一直複製粘貼,所以我們需要定義一個列印佛主函數: 帶有參數的函數 首先我們來定義一個函數來計算兩個數的總和: 這樣會不會有點太死板了,我們希望能夠從鍵盤輸入a ...
  • 什麼情況下使用ActiveMQ? 1 多個項目之間集成 (1) 跨平臺 (2) 多語言 (3) 多項目 2 降低系統間模塊的耦合度,解耦 軟體擴展性 3 系統前後端隔離 前後端隔離,屏蔽高安全區 安裝步驟: 第一步:安裝jdk,因為activemq依賴jdk來運行 請參照: Linux中安裝jdk ...
  • 安裝pyenv$ git clone git://github.com/yyuu/pyenv.git ~/.pyenv $ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc $ echo 'export PATH="$PYENV_ROOT/bi... ...
  • 在python中,有個好用的模塊linecache,該模塊允許從任何文件里得到任何的行,並且使用緩存進行優化,常見的情況是從單個文件讀取多行。linecache.getline(filename,lineno)從名為filename的文件中得到第lineno行示例:從final.txt文件中讀取數據 ...
  • Description 有一棵二叉樹,最大深度為D,且所有的葉子深度都相同。所有結點從上到下從左到右編號為1,2,3,…,2eD-1。在結點1處放一個小球,它會往下落。每個結點上都有一個開關,初始全部關閉,當每次有小球落到一個開關上時,它的狀態都會改變。當小球到達一個內結點時,如果該結點的開關關閉, ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...