Creating new threads in event callback - what about joining? - Raspberry Pi Forums


hello everybody

have thread questions can't figure out.

background story:
have tactile buttons, controlled raspberry, pigpio library , python programme.
when button pressed, callback function called. no problems there.

however, if keep button pressed, want start repeating function call, on ordinary keyboard.

first (naive) thought simple make loop in callback function, short sleep, , repeat action until have detected release of button. however, not work, because second event-callback (the button-release) not called until after first event has finished running. callbacks not run in parallel, 1 after in same thread. if loop-and-sleep during "keydown-event", keyrelease-event never run.

in stead have chosen launch new thread (i call "repeater") during key-down callback. thread repeats desired action until notified, key has been released. returns/exits.

works now. , happy.

problem is: happens these threads start? every time key pressed, start new thread, thread exits fine, when keys released, never join them. , that's why nervous.

eat ressources in way? have many buttons , other input-trigger-functions - many of spawn new threads, never joined. seems work fine here on desktop test, bit worried, run problems, when mount stuff , run in real world.

of course try, curious. correct way of creating new threads in callback functions? should keep track of them, , try join them on later callbacks? or can join them main thread, though wasn't main thread created them?

appreciate here. new this, , keep getting myself confused :-)

i consider different solution.

problem @ moment no further callbacks while button in stable state. solution start watchdog on gpio (http://abyz.co.uk/rpi/pigpio/python.html#set_watchdog).

callback button press , start watchdog @ key repeat rate. series of callback watchdog timeouts. whenever timeout call function. when callback button release cancel watchdog.

code: select all

#!/usr/bin/env python  import time import pigpio  button=4  pi = pigpio.pi() # connect pi  if not pi.connected:    exit()  def cbf(gpio, level, tick):    if level == 0:       print("button release") # stop button repeats       pi.set_watchdog(button, 0)    elif level == 1:       print("button press")       pi.set_watchdog(button, 200) # 5 repeats per second    else:       print("button repeat")  cb = pi.callback(button, pigpio.either_edge, cbf)  try:     while true:       time.sleep(1) # work done in callback  except keyboardinterrupt:    pass  print("\ntidying up")  pi.set_watchdog(button, 0) # stop button repeats cb.cancel() # cancel callback pi.stop() # disconnect pi 


raspberrypi



Comments