Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Running function in thread does not modify current_thread()

I'm currently trying to figure out how threads work in python.

I have the following code:

def func1(arg1, arg2):

    print current_thread()
    ....

class class1:

    def __init__():
        ....

    def func_call():
        print current_thread()
        t1 = threading.Thread(func1(arg1, arg2))
        t1.start()
        t1.join()

What I noticed is that both prints output the same thing. Why is the thread not changing?

like image 997
cpp_ninja Avatar asked Mar 17 '13 12:03

cpp_ninja


2 Answers

You are calling the function before it is given to the Thread constructor. Also, you are giving it as the wrong argument (the first positional argument to the Thread constructor is the group). Assuming func1 returns None what you are doing is equivalent to calling threading.Thread(None) or threading.Thread(). This is explained in more detail in the threading docs.

To make your code work try this:

t1 = threading.Thread(target=func1, args=(arg1, arg2))
t1.start()
t1.join()
like image 80
Michael Mauderer Avatar answered Sep 27 '22 23:09

Michael Mauderer


You're executing the function instead of passing it. Try this instead:

t1 = threading.Thread(target = func1, args = (arg1, arg2))
like image 32
robertklep Avatar answered Sep 28 '22 01:09

robertklep