Created
August 22, 2019 09:22
-
-
Save zmej-serow/52de5e94ea13fb6b4a4476f942ebd011 to your computer and use it in GitHub Desktop.
Background task running in separate thread
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
from time import sleep | |
from queue import Queue | |
from threading import Thread | |
# create a consumer | |
def consumer(input_queue): | |
while True: | |
# retrieve data from queue (blocking) | |
data = input_queue.get() | |
print("--task started") | |
# do something with the data | |
sleep(2) | |
print(data) | |
print("--task ended") | |
# report that data has been consumed | |
input_queue.task_done() | |
# create thread with task queue | |
queue = Queue() | |
thread = Thread(target=consumer, args=(queue, )) | |
thread.start() | |
# put data in queue | |
queue.put("I will be printed after 2 seconds") | |
# code execution will continue | |
print("I will be printed first!") | |
# now have to gracefully exit the background thread eventually |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment