user1530405
user1530405

Reputation: 455

Python thread can not be cancelled

I have a python thread which should display a message every second, while the rest of the script continues running. But the timer.cancel function does not work, as it still keeps running even after the main loop have been terminated:

from threading import *
import time
import sys

a = 0

def x():
    while(True):
        global a
        print
        print 'Beep', a
        print
        time.sleep(1)   # wait 1 second      

t = Timer(1.0, x)       # create thread
t.start()               # start thread

while True:
    a = a + 1
    print a
    time.sleep(0.1)

    if a > 30:    
        t.cancel()
    if a > 50:
        sys.exit()

What am I doing wrong ?

Upvotes: 2

Views: 487

Answers (2)

RAJ GUPTA
RAJ GUPTA

Reputation: 498

The problem with your threading code as much i can get is your beep part is executing with timer set to 1-sec even when your a=a+1 part is stop so simply what u can do is add a condition in beep part as:

    time.sleep(1)         
    if a>50:
      sys.exit()

This will stop the execution of thread and you will get your desired result This is simplest thing that u can do or else follow the zangw method() which works well for run and stop of thread

Upvotes: 0

zangw
zangw

Reputation: 48376

The threading.Timer class has one cancel method, but it won't cancel the thread, it will stop the timer from actually firing. Actually, the cancel method sets a threading.Event, and thread actually executing the threading.Timer will check that event after it's done waiting and before it actually executes the callback.

Here is maybe one solution to meet your requirement.

import threading
import time
import sys

a = 0

class TimerClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()

    def run(self):
        while not self.event.is_set():
            global a
            print
            print 'Beep', a
            print
            self.event.wait(1)

    def stop(self):
        self.event.set()

t = TimerClass()
t.start()

while True:
    a = a + 1
    print a
    time.sleep(0.1)

    if a > 30:    
        t.stop()
    if a > 50:
        sys.exit()

Upvotes: 2

Related Questions