How to delete a object that has a running tread

Viewed 24

How can I terminate the running thread once the object gets out of scope or is otherwise deleted?

import sys
import threading
import time

class C(threading.Thread):
    def __init__(self):
        self.running = True
        threading.Thread.__init__(self, daemon=False)
        self.start()

    def __del__(self):
        print("stop thread")
        self.running = False    

    def run(self):
        while self.running:
            print('running')
            time.sleep(2)    

c = C()
time.sleep(1)
print(f'ref count: {sys.getrefcount(c)}')
print("ref count > 1 del can not be called")
del(c)
0 Answers
Related