2017-06-25 8 views
1

私のアプリケーションはループ内で実行されています。時には、ループからledフラッシュ関数を呼び出す必要があります。私はこれほど多くをこのようにした。Pythonはサブ関数をスレッドする

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() 

これは動作しますが、def led_red_flashの部分にすべてのスレッドの内容を入れる日がありますか?スクリプトが複雑になるにつれて、読みにくくなります。そうですね。

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

上記は、実行しているループの非常に単純化されたバージョンです。実際のスクリプトでは、led_red_flashの複数のインスタンスを同時に実行することはできません。これは問題ではありません。

+0

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

あなたは設計レビューを求めている、またはあなたがプログラミングの問題がありますか? –

答えて

1

あなたはラッパー関数を作成することができます。

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 

をところで、あなたの元のコードは、別のスレッドでled_red_flashを実行しませんでした。私はちょうどled_red_flashled_red_flash(100))と呼んだ。

関数呼び出しの戻り値ではなく、関数自体を渡す必要があります。 threading.Threadを参照してください。

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

これは仕事です...私は自分でラッパーを試していましたが、議論のためにうまくいかなかったと思います。ありがとう。 –

関連する問題