Ejecuta cualquier ejemplo en nuestra consola interactiva: Abrir consola de Python →
Concurrencia con threading en Python
El módulo threading permite ejecutar múltiples hilos dentro del mismo proceso. Aunque Python tiene el GIL, los hilos son útiles para tareas de IO, servidores, scrapers y operaciones concurrentes. En esta guía aprenderás a crear hilos, sincronizarlos, usar locks, eventos, colas y patrones profesionales.
Tabla de contenidos
- Crear hilos
- Hilos con funciones
- Hilos con clases
- Locks y sincronización
- Eventos
- Colas thread-safe
- Daemon threads
- Ejercicios
- Mini‑proyecto
1. Crear hilos
import threading
def tarea():
print("Ejecutando hilo")
h = threading.Thread(target=tarea)
h.start()
h.join()
2. Hilos con funciones
import threading
import time
def contar(n):
for i in range(n):
print(i)
time.sleep(0.5)
t = threading.Thread(target=contar, args=(5,))
t.start()
t.join()
3. Hilos con clases
import threading
import time
class Worker(threading.Thread):
def run(self):
for i in range(3):
print("Trabajando...")
time.sleep(1)
w = Worker()
w.start()
w.join()
4. Locks y sincronización
import threading
lock = threading.Lock()
contador = 0
def incrementar():
global contador
for _ in range(10000):
with lock:
contador += 1
hilos = [threading.Thread(target=incrementar) for _ in range(5)]
for h in hilos: h.start()
for h in hilos: h.join()
print("Total:", contador)
5. Eventos
import threading
import time
evento = threading.Event()
def esperar():
print("Esperando señal...")
evento.wait()
print("Evento recibido")
t = threading.Thread(target=esperar)
t.start()
time.sleep(2)
evento.set()
6. Colas thread-safe
import threading
import queue
import time
q = queue.Queue()
def productor():
for i in range(5):
q.put(i)
time.sleep(1)
def consumidor():
while True:
item = q.get()
print("Consumido:", item)
q.task_done()
threading.Thread(target=productor).start()
threading.Thread(target=consumidor, daemon=True).start()
q.join()
7. Daemon threads
import threading
import time
def tarea():
while True:
print("Daemon activo")
time.sleep(1)
t = threading.Thread(target=tarea, daemon=True)
t.start()
time.sleep(3)
print("Fin del programa")
8. Ejercicios
- Crea un contador seguro con locks.
- Implementa un sistema productor‑consumidor.
- Usa eventos para coordinar hilos.
- Crea un hilo daemon que registre logs.
- Implementa un pool de hilos manual.
# pool manual
hilos = [threading.Thread(target=tarea) for _ in range(5)]
# evento
evento.wait()
9. Mini‑proyecto: Pool de workers con cola
import threading
import queue
import time
q = queue.Queue()
def worker(id):
while True:
tarea = q.get()
print(f"Worker {id} procesando {tarea}")
time.sleep(1)
q.task_done()
for i in range(3):
threading.Thread(target=worker, args=(i,), daemon=True).start()
for i in range(10):
q.put(f"Tarea {i}")
q.join()