簡體   English   中英

如何只在滿足特定條件時運行的while循環

[英]How to while loop that only run when certain condition is met

我想要一個只在滿足特定條件時運行的 while 循環。 例如,我需要循環條件 A if listposts:= 0 and listposts != listView:來檢查是否有新記錄。 如果找到新記錄,它將執行 function B並停止,直到再次滿足條件。

我是編程新手,我嘗試使用這段代碼,但它仍然無休止地循環。

while True:

    if listposts != 0 and listposts != listView:
        Condition = True
         while Condition == True :
                      function B()
                
                      Condition = False

我要實現的是循環會在1個循環后停止,等到條件滿足再循環。

對我來說,您似乎有類似生產者/消費者的情況。

恕我直言,你的循環沒問題。 這里應用的原理稱為輪詢。 輪詢通過不斷詢問來不斷尋找新項目。

以更 CPU 優化的方式(使用更少的 CPU)實現它的另一種方法需要同步。 當新元素可用於處理時,將發出同步 object(例如互斥鎖或信號量)信號。 然后可以停止處理線程(例如,Windows 上的WaitForSingleObject() ),釋放 CPU 用於其他事情。 當收到信號時,Windows 發現線程應該被喚醒,讓它再次運行。

Queue.get() 和 Queue.put()是內置同步的此類方法。

不幸的是,我看到許多開發人員改用 Sleep(),這不是完成這項工作的正確工具。

這是一個生產者/消費者示例:

from threading import Thread
from time import sleep
import random
import queue

q = queue.Queue(10)  # Shared resource to work on. Synchronizes itself
producer_stopped = False
consumer_stopped = False


def producer():
    while not producer_stopped:
        try:
            item = random.randint(1, 10)
            q.put(item, timeout=1.0)
            print(f'Producing {str(item)}. Size: {str(q.qsize())}')
        except queue.Full:
            print("Consumer is too slow. Consider using more consumers.")

def consumer():
    while not consumer_stopped:
        try:
            item = q.get(timeout=1.0)
            print(f'Consuming {str(item)}. Size: {str(q.qsize())}')
        except queue.Empty:
            if not consumer_stopped:
                print("Producer is too slow. Consider using more producers.")

if __name__ == '__main__':
    producer_stopped = False
    p = Thread(target=producer)
    p.start()

    consumer_stopped = False
    c = Thread(target=consumer)
    c.start()

    sleep(2)  # run demo for 2 seconds. This is not for synchronization!

    producer_stopped = True
    p.join()
    consumer_stopped = True
    c.join()

從您期望的行為來看,您需要三件事:

  1. 返回TrueFalse的條件測試(作為函數)
  2. 定期調用條件測試的循環
  3. 滿足條件時 function B()的條件調用(或條件測試 function 返回True
# list_posts can change and is used as parameter
# listView is a global variable (could also be defined as parameter)
# returns either True or Fals
def condition_applies(list_posts):
    return list_posts != 0 and list_posts != listView
# Note: method names are by convention lower-case
def B():  
    print("B was called")

# don't wait ... just loop and test until when ?
# until running will become False
running = True
while running:
   if condition_applies(listposts):
       print("condition met, calling function B ..")
       B()
   # define an exit-condition to stop at some time
   running = True

警告:這將是一個無限循環! 所以你需要在某個時間點設置running = False 否則循環將無限繼續並檢查條件是否適用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM