Python 如何杀死旧线程并启动新线程?

Python 如何杀死旧线程并启动新线程?,python,multithreading,raspberry-pi,Python,Multithreading,Raspberry Pi,我刚刚开始学习python,我对我的项目有问题。当我收到新消息并启动新线程时。旧线程仍在运行。 我想杀死旧线程,开始新线程。如何解决我的问题? (对不起,如果我英语不好,但我正在努力) 要终止python线程,需要退出函数。您可以在message=='ON'/'OFF'检查时删除。由于消息不会以任何方式更改(它被传递到函数led\u action),因此这些检查是不必要的。如果message是'ON'或'OFF',线程函数将进入无限循环,我怀疑这是您想要的。当函数返回时,它运行的线程将终止。除非

我刚刚开始学习python,我对我的项目有问题。当我收到新消息并启动新线程时。旧线程仍在运行。 我想杀死旧线程,开始新线程。如何解决我的问题? (对不起,如果我英语不好,但我正在努力)


要终止python线程,需要退出函数。您可以在message=='ON'/'OFF'检查时删除
。由于消息不会以任何方式更改(它被传递到函数
led\u action
),因此这些检查是不必要的。

如果
message
'ON'
'OFF'
,线程函数将进入无限循环,我怀疑这是您想要的。当函数返回时,它运行的线程将终止。除非您提供一种方法来通知代码该退出了,否则实际上没有办法停止正在运行的线程。这是一个例子。谢谢你的回答。我可以删除while message=='OFF',但我需要LED一直闪烁,直到message=='OFF',所以我必须设置while message=='ON'
def led_action(topic,message):
    print topic+" "+message

    if message == 'OFF':
        #state = False
        print ("Stoping...")
        while message == 'OFF':
            GPIO.output(8,GPIO.LOW)

    elif message == 'ON':
        #state = True
        print ("Opening...")
        while message == 'ON':
            GPIO.output(8,GPIO.HIGH)    #Set LED pin 8 to HIGH
            time.sleep(1)           #Delay 1 second
            GPIO.output(8,GPIO.LOW)     #Set LED pin 8 to LOW
            time.sleep(1)

# Get message form NETPIE and Do something 
def subscription(topic,message):
    set = thread.start_new_thread(led_action, (topic,message))

def connection():
    print "Now I am connected with netpie"

def disconnect():
     print "disconnect is work"

microgear.setalias("test")
microgear.on_connect = connection
microgear.on_message = subscription
microgear.on_disconnect = disconnect
microgear.subscribe("/mails")
microgear.connect(True)