Reputation: 21
I am just playing around with multi-threading, but I can't seem to get it to work. I have looked at other questions, but none really help me. Here's my code so far:
import threading, time
def hello():
for i in range(1,5):
time.sleep(1)
print("Hello")
def world():
for i in range(1,5):
time.sleep(1)
print("World")
newthread = threading.Thread(hello())
newthread.daemon = True
newthread.start()
otherthread = threading.Thread(world())
otherthread.daemon = True
otherthread.start()
print("end")
I expect to get something like:
Hello
World
Hello
World
Hello
World
Hello
World
end
But instead I get:
Hello
Hello
Hello
Hello
World
World
World
World
end
Upvotes: 1
Views: 1256
Reputation: 25813
You want something like this:
import threading, time
def hello():
for i in range(1,5):
time.sleep(1)
print("Hello")
def world():
for i in range(1,5):
time.sleep(1)
print("World")
newthread = threading.Thread(target=hello)
newthread.start()
otherthread = threading.Thread(target=world)
otherthread.start()
# Just for clarity
newthread.join()
otherthread.join()
print("end")
The joins tell the main thread to wait on the other threads before exiting. If you want the main thread to exit without waiting set demon=True
and don't join. The output might surprise you a little bit, it's not as clean as you might expect. For example I got this output:
HelloWorld
World
Hello
World
Hello
WorldHello
Upvotes: 1
Reputation: 36013
threading.Thread(hello())
You called the function hello
and passed the result to Thread
, so it executed before the thread object even existed. Pass the plain function object:
threading.Thread(target=hello)
Now the Thread
will be responsible for executing the function.
Upvotes: 2