yasar
yasar

Reputation: 13738

daemon threads in Python

After reading: http://pymotw.com/2/threading/#daemon-vs-non-daemon-threads I expect following code to terminate after 2 seconds:

from threading import Thread
from time import sleep

def a():
    i = 0
    while 1:
            print i
            i+=1



t = Thread(target=a)
t.setDaemon(True)
t.run()
sleep(2)

However, it keeps printing numbers forever. Am I missing something here? I am on win7. I get same behaviour from windows shell and idle.

Upvotes: 4

Views: 122

Answers (1)

viraptor
viraptor

Reputation: 34145

You should call t.start(), not t.run(). The first one will spawn a new thread and call run itself from there. Calling run on your own causes you to execute the a function in your current thread.

Upvotes: 4

Related Questions