1

I'm not sure why this does not work. The thread starts as soon as it is defined and seems to not be in an actual thread... Maybe I'm missing something.

import threading
import time

def endless_loop1():
    while True:
        print('EndlessLoop1:'+str(time.time()))
        time.sleep(2)

def endless_loop2():
    while True:
        print('EndlessLoop2:'+str(time.time()))
        time.sleep(1)

print('Here1')
t1 = threading.Thread(name='t1', target=endless_loop1(), daemon=True)
print('Here2')
t2 = threading.Thread(name='t2', target=endless_loop2(), daemon=True)
print('Here3')
t1.start()
print('Here4')
t2.start()

Outputs:

Here1
EndlessLoop1:1446675282.8
EndlessLoop1:1446675284.8
EndlessLoop1:1446675286.81

1 Answer 1

6

You need to give target= a callable object.

target=endless_loop1()

Here you're actually calling endless_loop1(), so it gets executed in your main thread right away. What you want to do is:

target=endless_loop1

which passes your Thread the function object so it can call it itself.

Also, daemon isn't actually an init parameter, you need to set it separately before calling start:

t1 = threading.Thread(name='t1', target=endless_loop1)
t1.daemon = True
Sign up to request clarification or add additional context in comments.

2 Comments

So if I wanted to pass an "argument" to the thread before execution I would have to declare the variable beforehand endless_loop1.args = x then target=endless_loop1 instead of target=endless_loop1(x)?
@s4w3d0ff no, the Thread constructor has an args parameter for that, so you can just say: Thread(name='t1', target=endless_loop1, args=(x,))

Your Answer

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.