0
from threading import Thread
import threading
import random
import time


class MyThread(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.count = 0

    def run(self):
        time.sleep(1)
        this_name = threading.current_thread().getName()
        print("%s has begin to eat" % this_name)
        while True:
            self.count += 1

            print("%s has eaten %s hambergurs" % (this_name, self.count))
            time.sleep(random.random()*4)


th1 = MyThread()
th2 = MyThread()

th1.start()
th2.start()


del th1
print("th1 is deleted")
print(th1)

The output of the code is the following:

th1 is deleted
Traceback (most recent call last):
File "D:/Data/data_file/pycharm_project/test/test.py", line 33, in
print(th1)
NameError: name 'th1' is not defined
Thread-1 has begin to eatThread-2 has begin to eat
Thread-2 has eaten 1 hambergurs
Thread-1 has eaten 1 hambergurs
Thread-2 has eaten 2 hambergurs
Thread-1 has eaten 2 hambergurs
Thread-1 has eaten 3 hambergurs
Thread-2 has eaten 3 hambergurs

So after the following code

del th1

th1 is deleted
but Thread-1 is still running

del th1

why the above code does not kill Thread-1?

Ben Yan
  • 9
  • 2
  • 1
    You deleted the variable `th1`, but the object it referred to still exists. – khelwood Mar 02 '22 at 08:44
  • 1
    Just FYI... killing threads is not generally a good practice. In general, it is often preferable to set an *"event"* that threads check and then exit gracefully if it is set. – Mark Setchell Mar 02 '22 at 08:49
  • See [Is there any way to kill a Thread?](https://stackoverflow.com/q/323972/3890632) – khelwood Mar 02 '22 at 08:50
  • See: https://stackoverflow.com/questions/18485098/python-threading-with-event-object – James Mar 02 '22 at 08:52

1 Answers1

0

if you insist on using del command you can you the following code:

class MyThread(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.count = 0
        self.__kill = False

    def run(self):
        time.sleep(1)
        this_name = self.name
        print("%s has begin to eat" % this_name)
        while not self.__kill:
            self.count += 1

            print("%s has eaten %s hambergurs" % (this_name, self.count))
            time.sleep(random.random()*4)

    def kill(self):
        self.__kill = True

    def __del__(self):
        self.__kill = True

and now you can use th1.kill() and del th1

p.s use self.name instead of threading.current_thread().getName()

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 02 '22 at 09:36