📢 Nuovo Corso Bootstrap Completo disponibile!

Esercizi Threading Python

Approfondisci le tue conoscenze sul threading in Python con questi esercizi introduttivi.

Esercizio 1

Creare un semplice thread che stampa i numeri da 1 a 10.
import threading
def print_numbers():
for i in range(1, 11):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()

Esercizio 2

Scrivere un programma che avvia due thread; uno stampa numeri pari e l'altro stampa numeri dispari fino a 10.
def print_even():
for i in range(2, 11, 2):
print(f"Pari: {i}")
def print_odd():
for i in range(1, 11, 2):
print(f"Dispari: {i}")
thread1 = threading.Thread(target=print_even)
thread2 = threading.Thread(target=print_odd)
thread1.start()
thread2.start()
thread1.join()
thread2.join()

Esercizio 3

Implementare un thread che esegue un countdown da 10 a 1 e stampa "Fine!" al termine.
def countdown():
for i in range(10, 0, -1):
print(i)
print("Fine!")
thread = threading.Thread(target=countdown)
thread.start()
thread.join()

Esercizio 4

Creare un thread che esegue un'operazione matematica semplice e restituisce il risultato tramite una coda.
from queue import Queue
import threading
def calculate_sum(q):
total = sum(range(1, 11))
q.put(total)
q = Queue()
thread = threading.Thread(target=calculate_sum, args=(q,))
thread.start()
thread.join()
result = q.get()
print("La somma è:", result)

Esercizio 5

Utilizzare un thread per monitorare lo stato di un'altra variabile modificata nel programma principale.
import threading
import time
stop_thread = False
def monitor_status():
while not stop_thread:
print("Monitoraggio in corso...")
time.sleep(1)
print("Monitoraggio terminato.")
thread = threading.Thread(target=monitor_status)
thread.start()
# Simula altre operazioni
time.sleep(5)
stop_thread = True
thread.join()

Esercizio 6

Scrivere un programma che avvia tre thread per stampare ognuno "Hello, World!" 5 volte.
def say_hello():
for _ in range(5):
print("Hello, World!")
threads = [threading.Thread(target=say_hello) for _ in range(3)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()

Esercizio 7

Creare un thread che stampa i primi 20 numeri della sequenza di Fibonacci.
def fibonacci():
a, b = 0, 1
for _ in range(20):
print(a)
a, b = b, a + b
thread = threading.Thread(target=fibonacci)
thread.start()
thread.join()

Esercizio 8

Implementare due thread che modificano una lista condivisa aggiungendo elementi.
import threading
shared_list = []
def add_items():
for i in range(5):
shared_list.append(i)
print(f"Elemento aggiunto: {i}")
thread1 = threading.Thread(target=add_items)
thread2 = threading.Thread(target=add_items)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Lista finale:", shared_list)

Esercizio 9

Utilizzare threading per calcolare simultaneamente somme di parti diverse di una stessa lista.
import threading
lista = list(range(1, 101))
risultati = []
def partial_sum(start, end):
total = sum(lista[start:end])
risultati.append(total)
print(f"Somma parziale: {total}")
thread1 = threading.Thread(target=partial_sum, args=(0, 50))
thread2 = threading.Thread(target=partial_sum, args=(50, 100))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Somma totale:", sum(risultati))

Esercizio 10

Creare un programma che utilizza i thread per stampare alternativamente "Ping" e "Pong".
import threading
import time
def ping():
while True:
time.sleep(1)
print("Ping")
def pong():
while True:
time.sleep(1)
print("Pong")
thread_ping = threading.Thread(target=ping)
thread_pong = threading.Thread(target=pong)
thread_ping.start()
thread_pong.start()
thread_ping.join(timeout=5)
thread_pong.join(timeout=5)
thread_ping._stop()
thread_pong._stop()
print("Ping Pong terminato.")