0

I'm just start learning about python and I have problem with my project to blink LED. when I get new message and start new thread. The old thread is still running. I want to kill old thread and start new thread. How to solve my problem? (Sorry if I'm not good in english but I'm trying)

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • If `message` is `'ON'` or `'OFF'` your thread function goes into an infinite loop—which I doubt is what you want. When the function returns, the thread it is running within will terminate. There really isn't a way to stop a thread that is running unless you provide a way to inform the code within that it's time to exit. This [this answer](http://stackoverflow.com/a/15734837/355230) for an example. – martineau Nov 20 '16 at 11:16

1 Answers1

-1

To terminate a python thread you need to exit your function. You can do this by removing your while message == 'ON'/'OFF' checks. As message doesn't change anyways (it is passed to the function led_action) those checks are unnecessary.

felinira
  • 1,644
  • 15
  • 21
  • thanks for your answer. I can remove while message == 'OFF' but I need LED blink all the time until message == 'OFF' so I have to set while message == 'ON' – Pangpoon1994 Nov 20 '16 at 11:18