Skip to content

Instantly share code, notes, and snippets.

@bauergeorg
Created March 9, 2021 11:13
Show Gist options
  • Save bauergeorg/33693d19b46f6efe473af381350b76ff to your computer and use it in GitHub Desktop.
Save bauergeorg/33693d19b46f6efe473af381350b76ff to your computer and use it in GitHub Desktop.
Pyhton: thread with queue
import threading
import queue
import time
q = queue.Queue()
def do_it_in_a_thread(arg):
t = threading.currentThread()
i = 0
while getattr(t, "do_run", True):
time.sleep(0.5)
q.put(i)
print('Put item on queue')
i += 1
print('Thread is active')
print("Stopping as you wish.")
if __name__ == "__main__":
# turn-on the thread
t1 = threading.Thread(target=do_it_in_a_thread, args=("task",))
t1.daemon = True
t1.start()
# get values from the queue
for i in range(5):
item = q.get()
print('Get item of queue')
print(item)
q.task_done()
# stop thread
t1.do_run = False
t1.join()
print('Thread stopped')
# clear queue
if not q.empty():
item = q.get()
print(item)
q.task_done()
# block until
q.join()
print('All work completed')
@bauergeorg
Copy link
Author

Terminal output:

Put item on queue
Thread is active
Get item of queue
0
Put item on queue
Thread is active
Get item of queue
1
Put item on queue
Thread is active
Get item of queue
2
Put item on queue
Thread is active
Get item of queue
3
Put item on queue
Thread is active
Get item of queue
4
Put item on queue
Thread is active
Stopping as you wish.
Thread stopped
5
All work completed

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