Home > database >  Stop child thread from main thread in python
Stop child thread from main thread in python

Time:12-13

I'm starting a webserver in a new thread. After all tests are run I want to kill the child thread with running server inside. The only one solution is interrupting entire process with all threads inside by calling "os.system('kill %d' % os.getpid())" (see the code below). I'm not sure it's the smartest solution. I'm not sure all threads will be killed after all. Could I send some kind of "Keyboard interrupt" signal to stop the thread before exiting main thread?

import http
import os
import sys
import unittest
import time

import requests
import threading

from addresses import handle_get_addresses, load_addresses
from webserver import HTTPHandler


def run_in_thread(fn):
    def run(*k, **kw):
        t = threading.Thread(target=fn, args=k, kwargs=kw)
        t.start()
        return t
    return run


@run_in_thread
def start_web_server():
    web_host = 'localhost'
    print("starting server...")
    web_port = 8808
    httpd = http.server.HTTPServer((web_host, web_port), HTTPHandler)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass


class TestAddressesApi(unittest.TestCase):

    WEB_SERVER_THREAD: threading.Thread = None

    @classmethod
    def setUpClass(cls):
        cls.WEB_SERVER_THREAD = start_web_server()
        pass

    @classmethod
    def tearDownClass(cls):
        print("shutting down the webserver...")
        # here someting like cls.WEB_SERVER_THREAD.terminate() 
        # instead of line below
        os.system('kill %d' % os.getpid())

    def test_get_all_addresses(self):
        pass

    def test_1(self):
        pass

if __name__ == "__main__":
    unittest.main()

CodePudding user response:

Maybe threading.Event is you wanted.

CodePudding user response:

Just found a solution. Daemon Threads stop executing when main thread stops working

  • Related