Skip to content

Instantly share code, notes, and snippets.

@tamanobi
Last active December 27, 2022 02:42
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 tamanobi/5ae3b1886a0ac4acfc51a7e95a9bfadd to your computer and use it in GitHub Desktop.
Save tamanobi/5ae3b1886a0ac4acfc51a7e95a9bfadd to your computer and use it in GitHub Desktop.
Graceful shutdown on Python threading
import threading
import time
import requests
import queue
threads: list[threading.Thread] = []
stop_cue = queue.Queue(maxsize=1)
def work(i: int):
r = requests.get("https://example.com", stream=True)
for content in r.iter_content(32):
if not stop_cue.empty():
print(f"break: {i}")
break
print(content)
time.sleep(0.5)
for i in range(0, 11):
th = threading.Thread(target=work, args=(i, ))
th.start()
threads.append(th)
try:
for th in threads:
th.join()
except KeyboardInterrupt:
stop_cue.put("owari")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment