1
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]
for i in p:
 i.start()

for i in p:
 i.join()

I am not sure if i am right, please correct me if I am not. I am expecting the output to be printed in this order hello hi and hello2. as i am expecting the two threads created to run parallely . but i am getting the below output, hello hello2 and hi. Thread2 is running only after completion of thread1. Am i doing anything wrong? or my understanding or threading wrong?

1
  • You are calling the functions and passing their result(s) directly to Thread()'s constructor. Commented May 14, 2015 at 5:13

1 Answer 1

3

You need to pass a function reference to the Thread() class constructor which takes a "keyword argument" called target (Default: None).

Passing the result of a function call (such as what you've done) will have undesired behaviour especially since the first argument to Thread() is actually 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]
for i in p:
    i.start()

for i 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 always be called with keyword arguments.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.