Last active
December 27, 2022 02:42
-
-
Save tamanobi/5ae3b1886a0ac4acfc51a7e95a9bfadd to your computer and use it in GitHub Desktop.
Graceful shutdown on Python threading
This file contains hidden or 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 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