简体   繁体   中英

How to kill old thread and start new thread?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM