sai kiran
sai kiran

Reputation: 37

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

Upvotes: 1

Views: 201

Answers (1)

James Mills
James Mills

Reputation: 19050

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.

Upvotes: 3

Related Questions