from threading import Thread
import time
def Function1():
print "11"
print "12"
time.sleep(5)
print "13"
print "14"
def Function2():
print "21"
print "22"
time.sleep(10)
print "23"
print "24"
for i in range(3)
t1= Thread(target=Function1())
t2= Thread(target=Function2())
t1.start()
t2.start()
Above program runs sequentially...
11
12
13
14
21
22
23
24
11
12
13
14
21
22
23
24
11
12
13
14
21
22
23
24
how to run two functions(threads) simultaneously?? I don't want to use multiprocessing.. I need to write python script for performance testing...for that i need threads to run simultaneously Is there any way to solve this problem?
Your problem is that the target=
keyword is now set to the return value of function. You want to have the function itself.
So, what is actually happening right now is:
Function1()
t1
has its target set to None
(return value of Function1()
Function2()
and t2
.t1
and t2
threads, which both has None
as target. This has no effect.Replace
t1= Thread(target=Function1())
t2= Thread(target=Function2())
with
t1= Thread(target=Function1)
t2= Thread(target=Function2)
If you want parallel execution of Python code on multiple cores, then your only hope is multiprocessing
. Since, as mentioned in another answer, the CPython interpreter only allows to execute one piece of Python code at the same time (see "Global Interpreter Lock").
There is a lot of information about this to be found online.