Reputation: 530
I'm using the example below to stop threads safely. But how do I stop all threads which are currently running, if I don't know exactly which threads are running?
class exampleThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
try:
print('this thread is running')
sleep(10)
finally:
print('example thread ended')
def get_id(self):
if hasattr(self, '_thread_id'):
return self._thread_id
for id, thread in threading._active.items():
if thread is self:
return id
def raise_exception(self):
thread_id = self.get_id()
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id,
ctypes.py_object(SystemExit))
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
print('Exception raise failure')
example = exampleThread('example')
example.start()
Now my thread is running. But how do I kill multiple threads at the same time, without knowing if they are running and example
is declared?
Upvotes: 1
Views: 446
Reputation: 1959
To kill a thread safely let it listen to a signal, it could be internal variable or queue
here we defined a method called "kill()" it will set the variable "running" to False if you need to kill the thread
import threading
from time import sleep
class exampleThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
self.running=True
def run(self):
try:
while self.running: # watch for incoming kill signal
print('this thread is running')
sleep(1)
finally:
print('example thread ended')
def kill(self): # self kill safely
self.running = False
def get_id(self):
if hasattr(self, '_thread_id'):
return self._thread_id
for id, thread in threading._active.items():
if thread is self:
return id
def raise_exception(self):
thread_id = self.get_id()
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id,
ctypes.py_object(SystemExit))
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
print('Exception raise failure')
example = exampleThread('example')
example.start()
sleep(2)
# alive = example.isAlive()
example.kill()
Upvotes: 1