tengo este código:Cómo utilizar múltiples hilos
import thread
def print_out(m1, m2):
print m1
print m2
print "\n"
for num in range(0, 10):
thread.start_new_thread(print_out, ('a', 'b'))
quiero crear 10 hilos, cada hilo se ejecuta la función print_out
, pero fallé. Los errores son los siguientes:
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
'thread.join()' se utiliza para esperar hasta que finalice el hilo. y noté que si no agrego las dos últimas líneas de código: 'para hilo en hilos: thread.join()', el programa también se ejecuta bien, y cada hilo se ejecuta en 'thread.start()' según la depuración , IOW si no agrego 'time.time (0.1)', no necesito agregar el código 'thread.join()' porque el programa esperará automáticamente el hilo para finalizar su tarea en 'thread.start()', ¿no? – Searene
@Mark No necesita agregar 'time.sleep (0.1)' en absoluto. Eso no es necesario. Sí, puede eliminar el código que llama a 'join' y el entorno de Python esperará a que se completen todos los hilos antes de finalizar la ejecución. Sin embargo, agregué las llamadas a 'join' porque espero que necesite, en algún momento en el futuro, saber cómo esperar a que un hilo complete su ejecución. Pero sí, simplemente puede omitir esas llamadas para 'unirse' en este sencillo ejemplo. –