Threading in Python
Very very similar to Java but with less code.
import threading
import datetime
import time
DELAY = 10
def hacertrabajo():
timeinit = datetime.datetime.now()
print("se inicia "+str(timeinit))
time.sleep(10)
print("se finaliza "+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))
th1 = threading.Thread(target=hacertrabajo,name="th-1")
th2 = threading.Thread(target=hacertrabajo,name="th-2")
th1.start()
th2.start()
print("no se espera")
if you execute the prgoram you will see that the output "no se espear" is writtein even without having finisthed both threads.
PS C:\Users\jordi\Documents\python\multithread> python multi.py
se inicia 2018-02-26 22:02:26.326352
start th1
se inicia 2018-02-26 22:02:26.328306
start th2
no se espera
se finaliza 2018-02-26 22:02:36.328301en 0:00:10.001949
se finaliza 2018-02-26 22:02:36.330257en 0:00:10.001951
to wait implement the call join(seconds) where seconds are the timeout , the time point the time when the control will arive to point join
import threading
import datetime
import time
DELAY = 10
def hacertrabajo():
timeinit = datetime.datetime.now()
print("se inicia "+str(timeinit))
time.sleep(10)
print("se finaliza "+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))
th1 = threading.Thread(target=hacertrabajo,name="th-1")
th2 = threading.Thread(target=hacertrabajo,name="th-2")
th1.start()
th2.start()
timeinit = datetime.datetime.now()
th1.join(5)
print("se finaliza th1 "+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))
th2.join(11)
print("se finaliza th2"+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))
Da el resultado siguiente.
PS C:\Users\jordi\Documents\python\multithread> python multi.py
se inicia 2018-02-26 22:22:31.651966
se inicia 2018-02-26 22:22:31.652945
se finaliza th1 2018-02-26 22:22:36.653236en 0:00:05.000291
se finaliza 2018-02-26 22:22:41.653288en 0:00:10.001322
se finaliza 2018-02-26 22:22:41.654265en 0:00:10.001320
se finaliza th22018-02-26 22:22:41.655247en 0:00:10.002302
PS C:\Users\jordi\Documents\python\multithread>
Tal y como indica la documentacion lo normal de join() seria despues hacer algo con el thread como