Reputation: 8477
watching David beazley's(http://www.dabeaz.com) video about python threads,I was trying out stuff with threads
def countdown(n):
while n > 0:
if not n % 100000:
print n
n -= 1
>> from threading import Thread
>> t1=Thread(target=countdown,args=(10000000,))
>> t1.start();t1.join()
>>Ctrl-C
this gave
>>10000000
9900000
9800000
9700000
9600000
Ctrl-C9500000
9400000
...
400000
300000
200000
100000
----------
KeyboardInterrupt :
...
Now I tried to find the status of the thread
>>t1.isAlive()
>>False
So,I tried to run the thread again, which caused an error
>>t1.start();t1.join()
--------------
RuntimeError: thread already started
Why does this happen? is there a way to stop the thread?
Upvotes: 2
Views: 237
Reputation: 1463
Python3 did repair the behaviour a little: You get an "thread can only be started once". This is by design.
If you want to have more control you may have a look at the _thread module, which is just a wrapper on the POSIX threads.
Upvotes: 2
Reputation: 21793
In the thread library you are using, a given instance of a thread can only be started and stopped once, and thereafter not started again. The error message you got was because you tried to start a thread after it had gotten stopped, so you did succeed in stopping it. To 'start the thread again' you must instantiate a brand new thread and start that instead.
Upvotes: 4