Skip to content

Instantly share code, notes, and snippets.

@zmej-serow
Created August 22, 2019 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmej-serow/52de5e94ea13fb6b4a4476f942ebd011 to your computer and use it in GitHub Desktop.
Save zmej-serow/52de5e94ea13fb6b4a4476f942ebd011 to your computer and use it in GitHub Desktop.
Background task running in separate thread
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