2
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?

Akshay Ambekar
  • 325
  • 1
  • 3
  • 14
  • When in doubt, blame the [GIL](https://en.wikipedia.org/wiki/Global_interpreter_lock). – erip Mar 17 '16 at 15:57

2 Answers2

2

how to run two functions(threads) simultaneously? I don't want to use multiprocessing..

Unfortunately, you can't really have these two simultaneously (or at least, you can't run things truly concurrently using threading). This is an inherent limitation of the CPython interpreter's GIL.

The only thing that threading gives is single-core context switching, where the interpreter will run a function on a single core, then swap it out temporarily and run a different function on single core, etc. This is possibly useful for applications that do something while, e.g., monitoring user input, but that's about it.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
2

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:

  1. Call Function1()
  2. t1 has its target set to None (return value of Function1()
  3. 1-2 repeated for Function2() and t2.
  4. Start 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.

Hannes Ovrén
  • 21,229
  • 9
  • 65
  • 75