2016-11-20 178 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