Created
March 13, 2023 18:26
-
-
Save KabakiAntony/43934e090a1e519b5bf3a07d47ed12ee to your computer and use it in GitHub Desktop.
real world example of threads
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 requests | |
from threading import Thread | |
class PDFDownloader(Thread): | |
def __init__(self, url, filename): | |
super().__init__() | |
self.url = url | |
self.filename = filename | |
def run(self): | |
response = requests.get(self.url) | |
with open(self.filename, "wb") as f: | |
f.write(response.content) | |
print(f"{self.filename} downloaded successfully!") | |
def main(): | |
urls = [ | |
"https://example.com/document1.pdf", | |
"https://example.com/document2.pdf", | |
"https://example.com/document3.pdf", | |
"https://example.com/document4.pdf", | |
"https://example.com/document5.pdf" | |
] | |
threads = [] | |
for i, url in enumerate(urls): | |
filename = f"document{i+1}.pdf" | |
thread = PDFDownloader(url, filename) | |
thread.start() | |
threads.append(thread) | |
for thread in threads: | |
thread.join() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment