1

I founded a nice package that is called kthread which simplify the threading in python. I have also found out that it is possible to name give a thread by its name etc:

import sys
import time

import kthread


def func():
    try:
        while True:
            time.sleep(0.2)
    finally:
        sys.stdout.write("Greetings from Vice City!\n")
        sys.stdout.flush()


t = kthread.KThread(target=func, name="KillableThread1")

t.start()
t.is_alive()
t.terminate()
t.is_alive()

Instead of doing t.terminate() I wonder if there is a possibility to remove a thread by given name?

PythonNewbie
  • 1,031
  • 1
  • 15
  • 33
  • You can store the threads in a dictionary, where the key is the `name` of the thread and the value the reference to the thread `t`. Then you can also remove it when the thread is terminate. – Thymen Apr 03 '21 at 15:46
  • The library you mentioned is extending the ```Threading.Thread``` class by adding methods like ```terminate``` to it. When you call ```terminate``` it raises an exception to kill the thread. I think this https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread and this https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html may help. – Wasim Zarin Apr 03 '21 at 15:49
  • @Thymen Right, im not quite sure how that would work though, is there an example you know how I can do that? I was thinking maybe there would be a way to via "api" call the specific name to terminate the specific thread? – PythonNewbie Apr 03 '21 at 15:51
  • @SunnyZarin Right, im not sure if that is a good thing or not? I do not follow it :( – PythonNewbie Apr 03 '21 at 15:52

1 Answers1

1

The following piece of code might help.

thread_dict = {}
t1 = kthread.KThread(target=func, name="KillableThread1")
t2 = kthread.KThread(target=func, name="KillableThread2")

thread_dict[t1.name] = t1
thread_dict[t2.name] = t2

After that when you want to kill a thread then do the following:


thread_dict["KillableThread1"].terminate()

Wasim Zarin
  • 166
  • 3
  • I guess you need to add `del thread_dict["KillableThread1"]` at the end to remove it from the list too right? Also I have aother question while at it, is it possible to terminate the KillableThread1 from another script in that case? If I example save the thread_dict in a database and remove it some how? – PythonNewbie Apr 03 '21 at 16:41
  • 1
    I doubt that will be a good idea and might not even be possible. Threads exist under a process and are assigned a certain task along with some termination conditions. Once the termination condition is met the thread is marked for removal. A Thread Scheduler then may remove that thread. I think allowing a thread in one process to be terminated by some thread in another process goes against a fundamental principle around which a Threading System is designed. – Wasim Zarin Apr 03 '21 at 17:06