1

My application is running a in a loop.. sometimes it needs to call a led flash function from the loop. I pretty much did that like this;

def led_red_flash(flashcount):
        logging.debug('Starting')

        for l in range(0,flashcount):
                GPIO.output(16,GPIO.HIGH)
                time.sleep(0.1)
                GPIO.output(16,GPIO.LOW)
                time.sleep(0.1)
        logging.debug('Stopping')

while True:
       <do some stuff here>
       t = threading.Thread(name='led_red_flash', target=led_red_flash(100) )
       t.start()

This works.. but would there be a day to put all the threading stuff in the def led_red_flash part? As my scripts gets more complex it will make it harder to read. So something like this;

while True:
       <do some stuff here>
       led_red_flash(100)

The above is a very simplified version of the loop I am running. In the actual script it would not be possible to have multiple instances of led_red_flash run at the same time.. so this is not an issue.

Alex van Es
  • 1,141
  • 2
  • 15
  • 27

1 Answers1

1

You can create a wrapper function:

def _led_red_flash(flashcount):
    logging.debug('Starting')
    for l in range(0,flashcount):
        GPIO.output(16,GPIO.HIGH)
        time.sleep(0.1)
        GPIO.output(16,GPIO.LOW)
        time.sleep(0.1)
    logging.debug('Stopping')


def led_red_flash(flashcount):
    t = threading.Thread(name='led_red_flash', target=_led_red_flash, args=(100,))
    t.start()
    return t

BTW, your original code didn't execute led_red_flash in a separate thread. I justed called led_red_flash (led_red_flash(100)).

You should pass the function itself, not the return value of the function call. See threading.Thread.

threading.Thread(name='led_red_flash', target=led_red_flash(100))

to

threading.Thread(name='led_red_flash', target=led_red_flash, args=(100,))
falsetru
  • 357,413
  • 63
  • 732
  • 636