I am confused why this code seems to hang and do nothing? As I try to experiment, it seems that I cannot get functions to access the queue from outside the function that added the item to the queue. Sorry, I am pretty novice. Do I need to pip install something? Update: Win10, Python 3.7.8, and this problem seems to apply to other variables besides queues.
This code works:
from multiprocessing import Queue, Process
q = Queue()
def main():
q.put('a')
q.put('b')
print(q.get(block=True) + ' gotten')
print(q.get(block=True) + ' gotten')
if __name__ == '__main__':
main()
This code does not work:
from multiprocessing import Queue, Process
q = Queue()
def main():
putter_process = Process(target=putter)
putter_process.start()
print(q.get(block=True) + ' gotten')
print(q.get(block=True) + ' gotten')
def putter():
q.put('a')
q.put('b')
if __name__ == '__main__':
main()
Similarly, this code from this question also hangs up on me:
import time
from multiprocessing import Process, Queue
sensor_data_queue = Queue()
def reads_sensor_data():
# Suppose we add a sensor reading every second; this simulates that. It runs 10 iterations. You could modify this
# to run forever, or until something tells it to quit.
for iteration in range(10):
sensor_data_queue.put(random.random()) # Generate a random number.
time.sleep(1) # Sleep for 1 second
sensor_data_queue.put(None) # None means we're done.
def analyze_sensor_data():
while 1:
data = sensor_data_queue.get(block=True)
if data is None:
break
else:
print(f'Analyzing {data}... Beep, beep, boop... {data * 100}')
print('All done!')
def main():
# Run the reader process in the background...
reader_process = Process(target=reads_sensor_data)
reader_process.start()
try:
analyze_sensor_data()
finally:
reader_process.join()
if __name__ == '__main__':
main()
EDIT: I am not sure this has to do with queues, because when I try to change a regular text variable it also doesn't work.
from multiprocessing import Queue, Process
import time
text = 'start'
def main():
putter_process = Process(target=putter)
putter_process.start()
time.sleep(2)
print(text)
def putter():
text = 'edited'
if __name__ == '__main__':
main()
The above outputs start
whereas I was expecting it to output edited