2016-11-20 177 views
0

我刚刚开始学习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) 
+0

如果'message'是'ON'或'OFF',你的线程函数会进入一个无限循环 - 我怀疑是你想要的。当函数返回时,它所运行的线程将终止。实际上没有办法阻止正在运行的线程,除非您提供了一种通知代码的方法,以便退出。这[这个答案](http://stackoverflow.com/a/15734837/355230)为例。 – martineau

回答

-1

要终止你需要退出你的函数蟒蛇线程。您可以通过删除您的while message == 'ON'/'OFF'检查来完成此操作。由于消息不会改变(它被传递给功能led_action),这些检查是不必要的。

+0

感谢您的回答。我可以删除while消息=='OFF',但我需要LED一直闪烁,直到消息=='OFF',所以我必须设置消息=='ON' – Pangpoon1994