0

I want a while loop that only run when certain condition is met. For example, I need to loop the condition A if listposts != 0 and listposts != listView: to check whether there is a new record or not. If it found a new record it will do function B and stop until the condition is met again.

I'm new to programming and I tried with this code but its still looping endlessly.

while True:

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

What I want to achieve is the loop will stop after 1 loop and wait until the condition is met to loop again.

terry555
  • 31
  • 9
  • 1
    `while `. If you're looking for a do-while loop, check the answers [here](https://stackoverflow.com/questions/743164/how-to-emulate-a-do-while-loop). – Maroun Aug 22 '21 at 11:59
  • 4
    Your code seems to do what you want according to the vague description. Please provide a [mre] of what you want to achieve – Tomerikoo Aug 22 '21 at 12:01
  • Does this answer your question? [How to emulate a do-while loop?](https://stackoverflow.com/questions/743164/how-to-emulate-a-do-while-loop) – Piero Aug 22 '21 at 12:08
  • 1
    @Piero I'm not sure this answers the question (I'm not completely sure what the question ***is***) but anyway if you think this question is a duplicate then please don't answer it. If anything, you should answer in the duplicate ***target*** (after you've made sure your answer doesn't already exist) – Tomerikoo Aug 22 '21 at 12:12
  • What is `listposts` and `listView` ? – cruisepandey Aug 22 '21 at 12:19
  • Where do `new records` come from ? When is the loop supposed to stop ? A `while True:` loop will run endlessly, that's probably what you don't want. – hc_dev Aug 22 '21 at 13:21

2 Answers2

0

To me it seems that you have a producer/consumer like situation.

IMHO your loop is ok. The principle applied here is called polling. Polling keeps looking for new items by constantly asking.

Another way of implementing this in a more CPU optimized way (using less CPU) requires synchronization. A synchronization object such as a mutex or semaphore will be signaled when a new element is available for processing. The processing thread can then be stopped (e.g. WaitForSingleObject() on Windows), freeing the CPU for other things to do. When being signaled, Windows finds out that the thread should wake up and let's it run again.

Queue.get() and Queue.put() are such methods that have synchronization built-in.

Unfortunately, I see many developers using Sleep() instead, which is not the right tool for the job.

Here's a producer/consumer example:

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()
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
0

From what you expect as behavior you need 3 things:

  1. a condition-test (as function) returning either True or False
  2. a loop that calls the condition-test regularly
  3. a conditional call of function B() when condition is met (or condition-test function returns 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

Warning: This will be an endless-loop! So you need at some point in time to set running = False. Otherwise the loop will continue infinite and check if condition applies.

hc_dev
  • 8,389
  • 1
  • 26
  • 38