multithreading in python not working as expected -
import threading import time def test1(): print "hello" time.sleep(15) print "hello2" def test2(): print "hi" th1 =threading.thread(test1()) th2 =threading.thread(test2()) p=[th1,th2] in p: i.start() in p: i.join()
i not sure if right, please correct me if not. expecting output printed in order hello hi , hello2. expecting 2 threads created run parallely . getting below output, hello hello2 , hi. thread2 running after completion of thread1. doing wrong? or understanding or threading wrong?
you need pass function reference thread()
class constructor takes "keyword argument" called target
(default: none
).
passing result of function call (such you've done) have undesired behaviour since first argument thread()
group=none
.
example: (corrected)
import threading import time def test1(): print "hello" time.sleep(15) print "hello2" def test2(): print "hi" th1 = threading.thread(target=test1) th2 = threading.thread(target=test2) p = [th1, th2] in p: i.start() in p: i.join()
output:
$ python foo.py hello hi # 15s delay hello2
see: threading.thread()
specifically:
class threading.thread(group=none, target=none, name=none, args=(), kwargs={})
this constructor should called keyword arguments.
Comments
Post a Comment