Calling a Method several times with several Threads

后端 未结 1 1663
孤独总比滥情好
孤独总比滥情好 2021-01-23 11:16

I want a LED to flash, while some work is beeing done on my Raspberry. I am using a Thread for the LED in my Python script.

The initial code:

import RPi.         


        
相关标签:
1条回答
  • 2021-01-23 12:10

    I found no logic fault and i confirm it works, but used the following changes:

    1. Starting the main_thread from inside if __name__ == '__main__':.
      I suggest to move also all GPIO calls inside this block.

    Avoid placing code that is executed on startup outside of if __name__ == '__main__':

    From the docs: Safe importing of main module One should protect the “entry point” of the program by using if __name__ == '__main__':

    1. Added join() after working = False, this guaranteed the thread has terminated befor starting it again.

      working = False  
      t.join()  
      

    I would suggest to change the def flash(), to the following:
    Using threading.Event() instead of a global Instance and passing it together with the pinLED. This generalizes the def flash(...) and allow its use with different pinLED, even parallel. Define status as threading.local() threadsafe, so instance’s values will be different for separate threads.
    For instance:

    def flash(pinLED, flashing):
        status = threading.local()
        status.LED = False
        while flashing.is_set():
            status.LED = not status.LED
            GPIO.output(pinLED, int(status.LED))
            time.sleep(0.5)
    
        GPIO.output(pinLED, 0)
    

    Changes to the main_thread:

    def main_thread():
        flashing = threading.Event()
        flashing.clear()
    
        try:
            while True:
                time.sleep(0.02)  
                if GPIO.input(pinButton) == 1:
                    t = threading.Thread(target=flash, args=(pinLED, flashing,))
                    flashing.set()
                    t.start()
    
                    time.sleep(2)  # work would be here
    
                    flashing.clear()
                    t.join()
        ...  
    

    Tested with Python:3.4.2

    0 讨论(0)
提交回复
热议问题