Created
March 9, 2021 11:13
-
-
Save bauergeorg/33693d19b46f6efe473af381350b76ff to your computer and use it in GitHub Desktop.
Pyhton: thread with queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Terminal output: