1
import threading
import time

def someMethod(x):
    time.sleep(20)
    print(x);

def someMethod2(x):
    time.sleep(1)
    print(x);

t1 = threading.Thread(name="t1", target=someMethod(1));
t2 = threading.Thread(name="t2", target=someMethod2(2));

t1.start();
t2.start();

I'd expect the output to be 2 followed by 1 but it is 1 followed by 2. Total time is 21 seconds. How can I make it run in parallel so the output is 2 followed by 1 and both threads run in parallel so the total time is 20 units?

Raj
  • 165
  • 3
  • 15

1 Answers1

7

You called the functions in the main thread and passed their return values as the thread entry point (since they both returned None, this meant a no-op entry point), you didn't actually run them in separate threads. You also called someMethod twice, and never called someMethod2. To fix, change to:

t1 = threading.Thread(name="t1", target=someMethod, args=(1,))
t2 = threading.Thread(name="t2", target=someMethod2, args=(2,))

which properly passes references to the functions themselves as the entry points, with the arguments to be used, deferring execution until the thread is actually launched.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271