简体   繁体   中英

How to terminate a running Thread in python?

I am using socket in this code to connect with other machine.I want to terminate thread when i get message from other machine but how to terminate Thread in Python ? I refer Many SO Questions and I found that there is no method in python to Close thread.Can anyone tell me the alternate way to close the thread ?

code:

from threading import Thread
import time
import socket

def background(arg):
    global thread
    thread = Thread(target=arg)
    thread.start()

def display():
    for i in range(0,20):
        print(i)
        time.sleep(5)

background(display)


s = socket.socket()
s.bind((ip,6500))
s.listen(5)
print("listening")

val,addr = s.accept()
cmd = val.recv(1024)
if cmd == "Terminate Process":
    print("Connected")
    thread.close()
    print("Process Closed")

Error:

AttributeError: 'Thread' object has no attribute 'close'

Short answer:

thread.join()

The rule of thumb is: don't kill threads (note that in some environments this may not even be possible, eg standard C++11 threads). Let the thread fetch the information and terminate itself. Controlling threads from other threads leads to hard to maintain and debug code.

Eg

SHOULD_TERMINATE = False

def display():
    for i in range(0,20):
        print(i)
        time.sleep(5)
        if SHOULD_TERMINATE:
            return

thread = Thread(target=display)
thread.start()

// some other code
if cmd == "Terminate Process":
    SHOULD_TERMINATE = True
    thread.join()

This is of course heavily simplified. Your code can be further refined with event objects (instead of .sleep ) or thread pools.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM