Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?

1 Answer

0 votes
by (106k points)
  • Yes it is possible to terminate a running thread but before terminating or killing thread you should think of the following cases:-

  1. Thread holds a critical resource that must be closed properly.

  2. When we create one thread it creates several threads that must be killed. 

  • So for handling this problem, we have a very nice way exit_request flag so that at regular intervals each thread check if it is time for it to exit.

  • Let’s understand this with an example:-

import threading 

class StoppableThread(threading.Thread):

def __init__(self): 

super(StoppableThread, self).__init__()

self._stop_event = threading.Event() 

def stop(self):

self._stop_event.set() 

def stopped(self):

return self._stop_event.is_set()

  • In this above code, you should call stop()on the thread when you want it to exit, and wait for the thread to exit properly using join(). The thread should check the stop flag at regular intervals.

 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 10, 2019 in Java by alan99 (830 points)
0 votes
1 answer

Browse Categories

...