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
2 Answers 2
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.
3 Comments
target=hello as parameters. This tells it to execute the function. Also add args=(arg1, arg2, arg3) for parameters.daemon = False or the script will exit before the threads finish.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
Comments
Explore related questions
See similar questions with these tags.