El hilo principal espera hasta que los hilos secundarios t1 y t2 hayan finalizado.
Podríamos leer t1.join() como: “no pasaré de aquí hasta que el hilo t1 no haya terminado”.
import threading
import logging
# logging.DEBUG es el nivel más bajo, usado para mensajes de depuración detallados.
# Con este nivel, se registrarán todos los mensajes desde DEBUG hasta CRITICAL
# El -10s indica que el nombre del hilo será alineado a la izquierda en un campo de 10 caracteres.
logging.basicConfig(level=logging.DEBUG, format='[%(threadName)-10s]: %(message)s')
def imprime_x(x, n):
logging.debug("INICIO")
for i in range(n):
logging.debug(x)
logging.debug("FIN")
t1 = threading.Thread(target=imprime_x, args=("norte", 5,))
t2 = threading.Thread(target=imprime_x, args=("sur", 10,))
t1.start()
t2.start()
# espera hasta que el hilo t1 haya finalizado
t1.join()
# espera hasta que el hilo t2 hay finalizado
t2.join()
#llega hasta aquí cuando los dos hilos han
logging.debug("Fin!")
[Thread-6 (imprime_x)]: INICIO [Thread-6 (imprime_x)]: norte [Thread-7 (imprime_x)]: INICIO [Thread-6 (imprime_x)]: norte [Thread-7 (imprime_x)]: sur [Thread-6 (imprime_x)]: norte [Thread-7 (imprime_x)]: sur [Thread-6 (imprime_x)]: norte [Thread-7 (imprime_x)]: sur [Thread-6 (imprime_x)]: norte [Thread-7 (imprime_x)]: sur [Thread-6 (imprime_x)]: FIN [Thread-7 (imprime_x)]: sur [Thread-7 (imprime_x)]: sur [Thread-7 (imprime_x)]: sur [Thread-7 (imprime_x)]: sur [Thread-7 (imprime_x)]: sur [Thread-7 (imprime_x)]: sur [Thread-7 (imprime_x)]: FIN [MainThread]: Fin!