1

I have a flask app, in that I have a button name start and a cancel button. I have a task to process. I am creating a new thread for it to run in background setting as daemon thread. since it is a long running task, I am trying to provide a cancel option for it.

Methods used as below:

  • I tried using Event by checking is_set() in while loop and on cancel button calling set()
  • I tried using signals by passing thread id (ident) and SIGTERM signal to pthread_kill()

for both methods when I click on cancel button, The task does not get cancel and executes completely.

 class BackgroundWorker(Thread):

     # event = Event() 
        
     def __init__(self, name: str, daemon: bool, a: str, b: str, c: int) -> None:
        
         self.a: str = a
         self.b: str = b
         self.c: int = c
         # self.event = Event()
         super().__init__(name=name, daemon=daemon)

     def run(self) -> None:
         
         while True:
             long_background_task(self.a, self.b, self.c)
             
   
 
 # Creating object            
 task = BackgroundWorker("task", True, a, b, c)
 task.start()

Is there any other way to terminate the running thread or what I am missing in the listed methods?

davidism
  • 121,510
  • 29
  • 395
  • 339
winter
  • 467
  • 2
  • 10
  • Does `long_background_task` check the event? You said "checking is_set() in while loop", but that's not going to do anything until `long_background_task` finishes. – user2357112 Feb 12 '23 at 00:51
  • Hi user2357112, Thanks. I have not passed the `is_set()` to `long_background_task`, earlier instead of `while True` I had `while not BackgroundWorker.event.is_set()` this was not working so I tried `while True` and inside `if event.is_set(): break` this also did not work. How to check event inside `long_background_task` ? – winter Feb 12 '23 at 01:08
  • I also tried passing `native_id` to `pthread_kill()` that also did not worked. – winter Feb 12 '23 at 01:11
  • You can declare a global variable in your main program. Your thread can test for the variable value instead of `while True`. The variable can then be re-set when the cancel button is pressed. For the most elegant method though look at https://stackoverflow.com/a/325528/2794417 – Galo do Leste Feb 12 '23 at 01:12

0 Answers0