Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python How to kill a thread?

Sigma

Coder
Hi,
I want to kill / stop a thread at an event, within my websocket class, how can this be done? Will the same thread, that was opened when the connection was made, also be killed?


Python:
import threading
from threading import Thread

import signal, sys, json
import os
import shutil
import logging
import time
import sqlite3
from sqlite3 import Error
from functools import partial
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
logger = logging.getLogger(__name__)

wss = []
PORTNUM = 8001

class Echo(WebSocket):

    def __init__(self, state):
        threading.Thread.__init__(self)

    def controll(self, state):
        # Loop
        while True:
            self.do_something(state)
            time.sleep(5)

    def do_something(self, state)
        for ws in wss:
            ws.sendMessage(sendMessage(calculatation_something(state) #Broadcast of messane

    def handleMessage(self):
        if self.data is None:
            self.data = ''

         data = (self.data)
         func(data)
         print("Echoing check received data: '%s'" % state)

    def handleConnected(self):
        #stop_threads = False
        print(self.address, 'connected')
        if self not in wss:
            wss.append(self)
            t2 = threading.Thread(target=self.controll, args=('on'))
            t2.start()
            for thread in threading.enumerate():
                print(thread.name)
        print("Connected")

    def handleClose(self):
        #stop_threads = True
        #self.t2.kill()
        #self.t2.join()
        #print('thread killed')
        wss.remove(self)
        print(self.address, 'closed')
        print("Disconnected")

       
def main():
    print("Websocket server on port %s" % PORTNUM)
    server = SimpleWebSocketServer('', PORTNUM, Echo)
    try:
        server.serveforever()
    finally:
        server.close()

if __name__ == "__main__":
    main()
 
Solution
@Sigma Example using a global variable to tell the thread to stop. Please note that there will be a time after 'thread_stop' is set to 'True' while the thread is still running as we have to wait for the thread to get to the code which checks the variable's value.

Python:
from threading import Thread
from time import sleep, time

def my_thread() -> None:
    while not thread_stop:
        sleep(1)
        print(f"Hello world from 'my_thread' {time() - start_time} second(s) after the program started.")
       
    print(f"'my_thread' is stopping {time() - start_time} second(s) after the program started.")
   
    return

thread_stop = False # A boolean value telling the thread if it should stop.
start_time = time()

print("Starting...
Threads are non-killable (or at least Python doesn't have a thread kill implementation by default). You could use global variables or variables in a specific file and have the thread periodically check the value of that variable. Or you can use processes if you don't mind separate processes, and called the `terminate` function on a process once you're done.
 
Threads are non-killable (or at least Python doesn't have a thread kill implementation by default). You could use global variables or variables in a specific file and have the thread periodically check the value of that variable. Or you can use processes if you don't mind separate processes, and called the `terminate` function on a process once you're done.
Thank you, could you give me a minimal example, I am a bit overwhelmed with this problem?

I didn't really want to use processes, as far as I've read, it's more complicated to implement than threading, unless you have an example that fits my problem?

How could I start the loop outside the class? I already tried to start the thread under __main__, but I couldn't get it to work.
 
@Sigma Example using a global variable to tell the thread to stop. Please note that there will be a time after 'thread_stop' is set to 'True' while the thread is still running as we have to wait for the thread to get to the code which checks the variable's value.

Python:
from threading import Thread
from time import sleep, time

def my_thread() -> None:
    while not thread_stop:
        sleep(1)
        print(f"Hello world from 'my_thread' {time() - start_time} second(s) after the program started.")
       
    print(f"'my_thread' is stopping {time() - start_time} second(s) after the program started.")
   
    return

thread_stop = False # A boolean value telling the thread if it should stop.
start_time = time()

print("Starting 'my_thread'.")

print("Giving 'my_thread' 10 seconds to run before stopping it.")

Thread(target=my_thread).start()

sleep(10)

print("Stopping 'my_thread'.")

thread_stop = True

print("Stopped 'my_thread'.")

1667244462067.png
 
Solution
Fantastisc, thank you very much! I have tested it with your idea and it seems to work:

#Before disconnecting
Code:
Loop!!!!!!!
MainThread
Thread-4
Thread-5

After disconnecting from my websocket server, it seems no thread is running any more.

Code:
    def handleClose(self):
        self.thread_stop = True
        time.sleep(5)
        for thread in threading.enumerate():
            print(thread.name)
        print('thread stop')
        wss.remove(self)
        print(self.address, 'closed')
        #self.temp_controll(512, 'stop')
        print("Disconnected")

Code:
MainThread

Again, thank you very much!

Code:
import threading
from threading import Thread

from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
logger = logging.getLogger(__name__)

wss = []
PORTNUM = 8001

class Echo(WebSocket):

    def __init__(self, state):
        threading.Thread.__init__(self)
        self.thread_stop = False

    def controll(self, state):
        # Loop
        while not self.thread_stop:
            self.do_something(state)
            time.sleep(5)

    def do_something(self, state)
        for ws in wss:
            ws.sendMessage(sendMessage(calculatation_something(state) #Broadcast of messane

    def handleMessage(self):
        if self.data is None:
            self.data = ''

         data = (self.data)
         func(data)
         print("Echoing check received data: '%s'" % state)

    def handleConnected(self):
        self.thread_stop = False
        print(self.address, 'connected')
        if self not in wss:
            wss.append(self)
            t2 = threading.Thread(target=self.controll, args=('on'))
            t2.start()
            for thread in threading.enumerate():
                print(thread.name)
        print("Connected")

    def handleClose(self):
        self.thread_stop = True
        print('thread stop')
        wss.remove(self)
        print(self.address, 'closed')
        print("Disconnected")

      
def main():
    print("Websocket server on port %s" % PORTNUM)
    server = SimpleWebSocketServer('', PORTNUM, Echo)
    try:
        server.serveforever()
    finally:
        server.close()
if __name__ == "__main__":
    main()
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom