Anurag Sharma
Anurag Sharma

Reputation: 5039

python thread weird behavior

I have a timer function which I am calling it in another function like this

import time
import threading
def f():
    while(True):
        print "hello"
        time.sleep(5)

def execute():
    t = threading.Timer(5,f)
    t.start()
    command = ''
    while command != 'exit':
        command = raw_input()
        if command == 'exit':
            t.cancel()

Even if after entering "exit" command, the function is printing "hello" I am not able to figure out Whats wrong with the code

Upvotes: 0

Views: 184

Answers (2)

Xevelion
Xevelion

Reputation: 869

class threading.Timer - cancel() - Doc-Link

Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage.

A very simple Version of what you are trying to accomplish could look like this.

import threading

_f_got_killed = threading.Event()

def f():
    while(True):
        print "hello"
        _f_got_killed.wait(5)
        if _f_got_killed.is_set():
            break

def execute():
    t = threading.Timer(5,f)
    t.start()
    command = ''
    while command != 'exit':
        command = raw_input()
        if command == 'exit':
            _f_got_killed.set()
            t.cancel()

execute()

For forcefully killing a thread look at this:

Is there any way to kill a Thread in Python?

Upvotes: 3

Shashank
Shashank

Reputation: 13869

You are using cancel wrong. In http://docs.python.org/2/library/threading.html, it states: "Timers are started, as with threads, by calling their start() method. The timer can be stopped (before its action has begun) by calling the cancel() method. The interval the timer will wait before executing its action may not be exactly the same as the interval specified by the user."

In your code, if you try to use cancel after the timed thread has already begun its execution (it will in 5 seconds), cancel accomplishes nothing. The thread will remain in the while loop in f forever until you give it some sort of forced interrupt. So typing "exit" in the first 5 seconds after you run execute works. It will successfully stop the timer before the thread even begins. But after your timer stops and your thread starts executing the code in f, there will be no way to stop it through cancel.

Upvotes: 2

Related Questions