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

时间:2016-11-20 09:50:24

标签: python multithreading raspberry-pi

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

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)

1 个答案:

答案 0 :(得分:-1)

要终止python线程,您需要退出您的功能。您可以通过删除while message == 'ON'/'OFF'支票来执行此操作。由于消息不会发生任何变化(它被传递给函数led_action),因此这些检查是不必要的。