Skip to content

Instantly share code, notes, and snippets.

@bauergeorg
Created March 9, 2021 11:10
Show Gist options
  • Save bauergeorg/18e9d4d0a16354f94ffaee85b4d7514e to your computer and use it in GitHub Desktop.
Save bauergeorg/18e9d4d0a16354f94ffaee85b4d7514e to your computer and use it in GitHub Desktop.
Python: process with a queue
import multiprocessing
import time
def to_it_in_a_process(q):
i = 0
while(1):
time.sleep(1)
q.put(i)
print('Put item on queue')
i += 1
print('Process is active')
if __name__ == "__main__":
q = multiprocessing.Queue()
# turn-on the process
p1 = multiprocessing.Process(target=to_it_in_a_process, args=(q,))
p1.daemon = True
p1.start()
# get values from the queue
for i in range(5):
item = q.get()
print('Get item of queue')
print(item)
# stop process
p1.terminate()
print('Process stopped')
# clear queue
if not q.empty():
item = q.get()
print(item)
# block until
q.close()
print('All work completed')
@bauergeorg
Copy link
Author

Terminal output:

Put item on queue
Get item of queue
0
Put item on queue
Get item of queue
1
Put item on queue
Get item of queue
2
Put item on queue
Get item of queue
3
Put item on queue
Get item of queue
4
Process stopped
All work completed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment