How NOT To Wait For A Thread To Finish In Python
Solution 1:
From the documentation, target
should be a callable:
target is the callable object to be invoked by the run() method
You are not passing your function to target
, you are passing the return value of your function, so the function runs as soon as you pass it to threading.Thread
, not when you call t.start()
.
You should be using the args
parameter to specify arguments to your callable.
Simply change this line:
t = threading.Thread(target=whatever(i))
to
t = threading.Thread(target=whatever, args=(i,))
Solution 2:
you seem to not realize what this line does: t = threading.Thread(target=whatever(i))
, removing the parenthesis is not simply to not wait for the thread to finish its so you can actually start the function in a seperate thread:
target
should be the function object itself, but when you do t = threading.Thread(target=whatever(1))
, the target
will be the return value of whatever
that you already ran in your original thread, you need to give threading
the function itself then specify the parameters seperately and it will call it for you like this:
from time import sleep
import threading
def whatever(i):
sleep(5)
print("Hey! It's me number " + str(i))
for i in range(3):
t = threading.Thread(target=whatever, args=(i,))
t.start()
Solution 3:
from time import sleep
import threading
def whatever(i):
print("Hey! It's me number " + str(i))
for i in range(3):
t = threading.Thread(target=whatever, args=(i,))
t.start()
You have to consider one thing though.
In Python we have something called GIL - Global Interpreter Lock. It's something that, in short, makes it possible for only one thread of your python application, to execute in a given interpreter at once. What does it mean?
That it's not quite that easy do achieve true concurrency in Python - while it may seem like the instructions are being executed simultaneously because of the super quick CPUs we have today, they are, in fact, not.
Solution 4:
Just wrap it into a lambda.
from time import sleep
import threading
def whatever(i):
sleep(5)
print("Hey! It's me number " + str(i))
for i in range(3):
t = threading.Thread(target=lambda: whatever(i))
t.start()
Post a Comment for "How NOT To Wait For A Thread To Finish In Python"