Ivan219
Posts: 118
Joined: Sun Jul 05, 2015 10:01 pm

Stop thread instantly

Sat Jan 02, 2016 10:55 pm

Hello, I do program with two threads:

Code: Select all

 while True:
     input_state = GPIO.input(GPIO_but)
     if (input_state == True):
         print('Button Pressed')
         if (ways==1):
             ways=2
             w1.stop()//python hasn't this function
             w2.start()
         else:
             ways=1
             w2.stop()//python hasn't this function
             w1.start()
         time.sleep(1)
I have two ways flashing LEDs, in this ways functions I use time.sleep function, how stop thread instantly? I want to stop w1 and start w2 without waiting time.sleep in w1. How I can do this?

Ivan219
Posts: 118
Joined: Sun Jul 05, 2015 10:01 pm

Re: Stop thread instantly

Sun Jan 03, 2016 9:50 am

Any ideas?

User avatar
joan
Posts: 14935
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Stop thread instantly

Sun Jan 03, 2016 9:54 am

What two threads? Are you sure you are using threads?

Ivan219
Posts: 118
Joined: Sun Jul 05, 2015 10:01 pm

Re: Stop thread instantly

Sun Jan 03, 2016 5:21 pm

Yes, I use threads, but I don't know is it solution ot not, my task: I have three leds and two mode, I want to change mode with button, when I press button - mode change, but in modes I use time.sleep(), how change mode instantly? After press button.

PiGraham
Posts: 3932
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: Stop thread instantly

Sun Jan 03, 2016 5:42 pm

You could have the threads running all the time and testing your ways variable so that one does it's thing when ways == 1 and the other does its thing when ways==2.
Do many small sleeps to make it more responsive. If you Sleep(0.1) and count ten iterations you have one second but respond to a change of control within 100ms. You can also use time functions to change state when 1 second has elapsed.
It's good practice to make your threads clean up for themselves and self-terminate.

Return to “Beginners”