1

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
asked Jun 7, 2016 at 20:52

2 Answers 2

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.

answered Jun 7, 2016 at 21:01
Sign up to request clarification or add additional context in comments.

3 Comments

After removing the brackets, I now get this error: newthread = threading.Thread(hello, None) AssertionError: group argument must be None for now
add target=hello as parameters. This tells it to execute the function. Also add args=(arg1, arg2, arg3) for parameters.
You also need daemon = False or the script will exit before the threads finish.
1

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
answered Jun 7, 2016 at 21:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.