s4w3d0ff
s4w3d0ff

Reputation: 1190

Threading an endless while loop in Python 2

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

Upvotes: 1

Views: 1815

Answers (1)

tzaman
tzaman

Reputation: 47790

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

Upvotes: 6

Related Questions