how to Kill my thread

Dolamite Jenkins
Dolamite Jenkins used Ask the Experts™
I am running a thread that constantly listen on my port but the problem is when I shut the program down the thread may continue to run so when I restaart I get an error ... Im reading on the web I should kill the thread but ask it to stop but I cant find any examples

class ThreadClass(threading.Thread):
    def run(self):

        host = ''
	port = 51269
	backlog = 5
	size = 1000000
	addr = (socket.gethostname(), port)
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You might want to try the following function to the end of your script:
def join(self,timeout=None):
    if self.s:

Open in new window

Short answer.

Individual Python threads cannot be killed with an explicit command.
You can only politely ask a thread to terminate itself.

Normally all daemon threads should terminate when your program ends.

Did you declaret the thread as a daemon thread???

You can read about daemon threads in

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

If declaring as a daemon thread doens't work, then you can try following:

import os # at the beginning of your file, where you do all your imports

Open in new window

At the place where your program shuts down:

os._exit(0)  # pleace not the leading '_' character before the word exit

Open in new window



Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial