I want make a while loop to wait and continue only when it receives signal
For example in while.py
while queue:
#wait until signal
#bla bla
And when I hit button on my flask server it should send signal to this loop to continue: in main.py
def alarm():
#trigger loop to continue
Is there a way to do it?
You need to understand the simple producer-consumer example, (see source)
from threading import Thread, Lock
import time
import random
queue = []
lock = Lock()
class ProducerThread(Thread):
def run(self):
nums = range(5) #Will create the list [0, 1, 2, 3, 4]
global queue
while True:
num = random.choice(nums) #Selects a random number from list [0, 1, 2, 3, 4]
lock.acquire()
queue.append(num)
print "Produced", num
lock.release()
time.sleep(random.random())
class ConsumerThread(Thread):
def run(self):
global queue
while True:
lock.acquire()
if not queue:
print "Nothing in queue, but consumer will try to consume"
num = queue.pop(0)
print "Consumed", num
lock.release()
time.sleep(random.random())
ProducerThread().start()
ConsumerThread().start()
We started one producer thread (hereafter referred as producer) and one consumer thread (hereafter referred as consumer). The producer keeps adding to the queue while consumer keeps on removing from the queue. Since queue
is a shared variable, we keep it inside the lock to avoid a race condition.
At some point, the consumer has consumed everything and the producer is still sleeping. The consumer tries to consume more but since queue
is empty, an IndexError
is raised. But on every execution, before the IndexError
is raised you will see the print statement for "Nothing in queue, but consumer will try to consume", which explains why you are getting the error.