🧶 Semaphores
🎯 Objectif pédagogique
- Utiliser les semaphores pour limiter l'accès aux ressources.
📜 Énoncé
Écrire une classe Downloader
qui télécharge des fichiers depuis une liste
d'URLs en utilisant un nombre limité de threads. C'est à dire que si le nombre
de threads maximum est atteint, les autres threads doivent attendre qu'une place
se libère. Voici un bout de code pour vous aider.
import threading
class Downloader:
def __init__(self, max_threads=5):
self.max_threads = max_threads
self.semaphore = threading.Semaphore(max_threads)
def download_file(self, url):
pass # Votre code ici. Vous pouvez simuler le téléchargement avec time.sleep()
threads = []
downloader = Downloader(max_threads=3)
urls = [f"http://example.com/file{i}.txt" for i in range(10)]
for url in urls:
thread = threading.Thread(target=downloader.download_file, args=(url,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print("Tous les téléchargements sont terminés.")