Reputation: 1277
In this question, he actually asked something like what I want. Except that the answer was to remove the parentheses. However if I remove the parentheses, then I'll not be able to pass arguments for my functions.
How can I do the following simple code without waiting:
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(i))
t.start()
Desired output would be
Hey! It's me number 0
Hey! It's me number 1
Hey! It's me number 2
All printed at the same time
Upvotes: 0
Views: 4694
Reputation: 51165
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,))
Upvotes: 4
Reputation: 1745
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()
Upvotes: 1
Reputation: 1512
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()
Upvotes: 2
Reputation: 164
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.
Upvotes: 1