python wait方法_Python條件類| 帶有示例的wait()方法

python wait方法

Python Condition.wait()方法 (Python Condition.wait() Method)

wait() is an inbuilt method of the Condition class of the threading module in Python.

wait()是Python中線程模塊的Condition類的內置方法。

Condition class implements condition variable objects. A condition variable allows one or more threads to wait until they are notified by another thread. wait() method is used to block the thread and wait until some other thread notifies it by calling the notify() or notify_all() method or if the timeout occurs. The method returns a True Boolean value if it is released by notify() or notify_all() method otherwise a timeout happens, in that case, it returns False. If you wait on an unacquired lock, a Runtime Error is raised.

條件類實現條件變量對象 。 條件變量允許一個或多個線程等待,直到被另一個線程通知為止。 wait()方法用于阻塞線程,并等待直到其他線程通過調用notify()或notify_all()方法通知該線程或發生超時。 如果方法是通過notify()或notify_all()方法釋放的,則該方法返回True布爾值,否則會發生超時,在這種情況下,它將返回False。 如果等待未獲得的鎖定,則會引發“運行時錯誤”。

Read about Producer-Consumer here: Condition.acquire() Method

在這里閱讀有關Producer-Consumer的信息: Condition.acquire()方法

Module:

模塊:

    from threading import Condition

Syntax:

句法:

    wait(timeout=None)

Parameter(s):

參數:

  • timeout: It is an optional parameter, which specifies the time for which the thread will wait for a notify call. Its default value is None.

    timeout :這是一個可選參數,它指定線程等待通知調用的時間。 其默認值為無。

Return value:

返回值:

The return type of this method is <class 'bool'>. It returns True if it gets notified by the notify() method within given time. In case of a timeout, it returns False.

此方法的返回類型為<class'bool'> 。 如果在指定時間內通過notify()方法得到通知,則返回True。 如果超時,則返回False。

Example:

例:

# Python program to explain the
# use of wait() method for Condition object
import threading
import time
import random
class subclass:
# Initialising the shared resources
def __init__(self):
self.x = []
# Add an item for the producer
def produce_item(self, x_item):
print("Producer adding an item to the list")
self.x.append(x_item)
# Consume an item for the consumer
def consume_item(self):
print("Consuming from the list")
consumed_item = self.x[0]
print("Consumed item: ", consumed_item)
self.x.remove(consumed_item)
def producer(subclass_obj, condition_obj):
# Selecting a random number from the 1 to 3
r = random.randint(1,3)
print("Random number selected was:", r)
# Creting r number of items by the producer
for i in range(1, r):
print("Producing an item, time it will take(seconds): " + str(i))
time.sleep(i)
print("Producer acquiring the lock")
condition_obj.acquire()
try:
# Produce an item
subclass_obj.produce_item(i)
# Notify that an item  has been produced
condition_obj.notify()
finally:
# Releasing the lock after producing
condition_obj.release()
def consumer(subclass_obj, condition_obj):
condition_obj.acquire()
while True:
try:
# Consume the item 
subclass_obj.consume_item()
except:
print("No item to consume, list empty")
print("Waiting for 10 seconds")
# wait with a maximum timeout of 10 sec
value = condition_obj.wait(10)
if value:
print("Item produced notified")
continue
else:
print("Waiting timeout")
break
# Releasig the lock after consuming
condition_obj.release()
if __name__=='__main__':
# Initialising a condition class object
condition_obj = threading.Condition()
# subclass object
subclass_obj = subclass()
# Producer thread
pro = threading.Thread(target=producer, args=(subclass_obj,condition_obj,))
pro.start()
# consumer thread
con = threading.Thread(target=consumer, args=(subclass_obj,condition_obj,))
con.start()
pro.join()
con.join()
print("Producer Consumer code executed")

Output:

輸出:

Random number selected was: 3
Producing an item, time it will take(seconds): 1
Consuming from the list
No item to consume, list empty
Waiting for 10 seconds
Producer acquiring the lock
Producer adding an item to the list
Item produced notified
Consuming from the list
Consumed item:  1
Consuming from the list
No item to consume, list empty
Waiting for 10 seconds
Producing an item, time it will take(seconds): 2
Producer acquiring the lock
Producer adding an item to the list
Item produced notified
Consuming from the list
Consumed item:  2
Consuming from the list
No item to consume, list empty
Waiting for 10 seconds
Waiting timeout
Producer Consumer code executed

翻譯自: https://www.includehelp.com/python/condition-wait-method-with-example.aspx

python wait方法

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/378836.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/378836.shtml
英文地址,請注明出處:http://en.pswp.cn/news/378836.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

return編程python_python3 第二十一章 - 函數式編程之return函數和閉包

我們來實現一個可變參數的求和。通常情況下&#xff0c;求和的函數是這樣定義的&#xff1a;def calc_sum(*args):ax0for n inargs:ax ax nreturn ax但是&#xff0c;如果不需要立刻求和&#xff0c;而是在后面的代碼中&#xff0c;根據需要再計算怎么辦&#xff1f;可以不返回…

黑色背景下,計算照片白色的區域面積和周長

黑色背景下&#xff0c;計算照片白色的區域面積和周長 import cv2 img cv2.imread(E:\Python-workspace\OpenCV\OpenCV/beyond.png,1)#第一個參數為選擇照片的路徑&#xff0c;注意照片路徑最后一個為正斜杠其他都為反斜杠&#xff1b;第二個參數&#xff0c;其中1表示所選照…

php連接mssql數據庫的幾種方式

數據庫查詢不外乎4個步驟&#xff0c;1、建立連接。2、輸入查詢代碼。3、建立查詢并取出數據。4、關閉連接。 php連接mssql數據庫有幾個注意事項&#xff0c;尤其mssql的多個版本、32位、64位都有區別。 首先&#xff0c;php.ini文件中;extensionphp_pdo_mssql.dll ;extensionp…

通俗易懂:快速理解P2P技術中的NAT穿透原理

目錄1、基礎知識1.1、什么是NAT&#xff1f;1.2、為什么會有NAT&#xff1f;1.3、NAT有什么優缺點&#xff1f;2、NAT的實現方式2.1、靜態NAT2.2、NAPT3、NAT的主要類型3.1、完全錐型NAT&#xff08;Full Cone NAT&#xff0c;后面簡稱FC&#xff09;3.2、受限錐型NAT&#xff…

duration java_Java Duration類| toNanos()方法與示例

duration javaDuration Class toNanos()方法 (Duration Class toNanos() method) toNanos() method is available in java.time package. toNanos()方法在java.time包中可用。 toNanos() method is used to convert this Duration into the number of nanoseconds. toNanos()方…

java 負載均衡_java負載均衡 - 歲月靜好I的個人空間 - OSCHINA - 中文開源技術交流社區...

作用對系統的高可用&#xff0c;網絡壓力的緩解&#xff0c;處理能力擴容的重要手段之一。服務器負載我們通常所說的負載是指&#xff1a;服務器負載軟硬件負載服務器負載又分為&#xff1a;軟件負載--硬件負載軟件負載&#xff1a;通過在服務器上安裝一些具有負載功能或模塊的…

b tree和b+tree_B TREE實施

b tree和btreeB TREE及其操作簡介 (Introduction to B TREE and its operations) A B tree is designed to store sorted data and allows search, insertion and deletion operation to be performed in logarithmic time. As In multiway search tree, there are so many nod…

黑色背景下,將照片內封閉空心圖案的空心區域染成Cyan并保存

在黑色背景下&#xff0c;將照片內封閉空心圖案的空心區域染色 import cv2 import numpy as np img cv2.imread(E:\Python-workspace\OpenCV\OpenCV/beyond.png,1)#第一個參數為選擇照片的路徑&#xff0c;注意照片路徑最后一個為正斜杠其他都為反斜杠&#xff1b;第二個參數…

Ubuntu輸入su提示認證失敗的解決方法

Ubuntu輸入su提示認證失敗的解決方法 啟動ubuntu服務時竟然提示權限不夠&#xff0c;用su切換&#xff0c;輸入密碼提示認證失敗&#xff0c;這下搞了吧&#xff0c;后來一經查閱原來Ubuntu安裝后&#xff0c;root用戶默認是被鎖定了的&#xff0c;不允許登錄&#xff0c;也不允…

SDP協議基本分析(RTSP、WebRTC使用)

目錄一、介紹二、標準 SDP 規范1. SDP 的格式2. SDP 的結構&#xff08;1&#xff09;會話描述&#xff08;2&#xff09;媒體描述三、WebRTC 中的 SDP一、介紹 SDP&#xff08;Session Description Protocal&#xff09;以文本描述各端&#xff08;PC 端、Mac 端、Android 端…

MFC六大關鍵技術(第四部分)——永久保存(串行化)

MFC 六大關鍵技術 ( 第四部分 ) ——永久保存&#xff08;串行化&#xff09; 先用一句話來說明永久保存的重要&#xff1a;弄懂它以后&#xff0c;你就越來越像個程序員了&#xff01; 如果我們的程序不需要永久保存&#xff0c;那幾乎可以肯定是一個小玩兒。那怕我們的記事本…

在網絡中配置思科交換機

By default, all ports of a switch are enabled. As we are talking about layer 2 switching, there is no need to configure IP address or any routing protocol on the switch. In such a situation, the configuration is not focused on the switch. 缺省情況下&#…

黑色背景下,描繪照片的輪廓形狀并保存

描繪照片的輪廓形狀并保存 import cv2 from matplotlib import pyplot as plt # 1.先找到輪廓 img cv2.imread(E:\Python-workspace\OpenCV\OpenCV/beyond.png, 0) _, thresh cv2.threshold(img, 0, 255, cv2.THRESH_BINARY cv2.THRESH_OTSU) image, conturs, hierarchy c…

java pdf合并_Java 合并、拆分PDF文檔

本文將介紹如何在Java程序中合并及拆分PDF文檔&#xff0c;合并文檔時&#xff0c;包括合并多個不同PDF文檔為一個文檔&#xff0c;以及合并PDF文檔的不同頁面為一頁&#xff1b;拆分文檔是&#xff0c;包括將PDF文檔按每一頁拆分&#xff0c;以及按指定頁數范圍來拆分。下面將…

HDU4405 期望

對于期望&#xff0c;首先&#xff0c;對于這個公式中p表示概率&#xff0c;x表示隨機變量 展開則為 ex p1*x1p2*x2p3*x3....... 對于本題 假設 ex[ i ]表示當前 i 走到 n 的期望值。所以若 i 處沒有飛機&#xff0c;ex[ i ]sigma(1/6*ex[ik])1 其中(k1...6) &#xff08;1表示…

調用本地電腦攝像頭并進行按P進行捕獲照片并保存,按下Q退出

調用本地電腦攝像頭并進行按P進行捕獲照片并保存&#xff0c;按下Q退出 灰度攝像頭顯示&#xff1a; import cv2 cap cv2.VideoCapture(0) if not cap.isOpened():print("Cannot open camera")exit() while True:# 逐幀捕獲ret, frame cap.read()# 如果正確讀取幀…

intersect函數_PHP array_intersect()函數與示例

intersect函數PHP array_intersect()函數 (PHP array_intersect() Function ) array_intersect() function is used to find the matched elements from two or more elements. Function “array_intersect()” compares the values of the first array with the other arrays …

很全的SQL注入語句

1、返回的是連接的數據庫名and db_name()>02、作用是獲取連接用戶名and user>03、將數據庫備份到Web目錄下面;backup database 數據庫名 to diskc:\inetpub\wwwroot\1.db;--4、顯示SQL系統版本and 1(select VERSION) 或and 1convert(int,version)--5、判斷xp_cmdshell擴展…

使用DataTable更新數據庫

1、修改數據 DataRow dr hRDataSet.Tables["emp"].Rows.Find(textBox3.Text);//DataRow dr hRDataSet.Tables["emp"].Select("id"textBox3.Text)[0];dr.BeginEdit();dr["name"] textBox1.Text;dr.EndEdit();SqlCommandBuilder cmdn…

java異常體系_JAVA異常體系結構詳解

一、什么是異常異常&#xff1a;程序在運行過程中發生由于硬件設備問題、軟件設計錯誤等導致的程序異常事件。(在Java等面向對象的編程語言中)異常本身是一個對象&#xff0c;產生異常就是產生了一個異常對象。 ——百度百科二、異常體系Java把異常當作對象來處理&#xf…