简体   繁体   English

如何在python中终止正在运行的线程?

[英]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 ?我在此代码中使用套接字与其他机器连接。当我从其他机器收到消息时,我想终止线程,但如何在 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 ?我参考了 Many SO Questions,我发现 python 中没有关闭线程的方法。谁能告诉我关闭线程的替代方法?

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).经验法则是:不要杀死线程(请注意,在某些环境中,这甚至可能是不可能的,例如标准 C++11 线程)。 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.您可以使用 事件对象(而不是.sleep )或线程池进一步细化您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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