イベント#
導入#
イベントを使用すると、イベントオブジェクトを使って関数を並列実行できます。関数やスレッドを一つずつ呼び出す代わりに、イベントを使うと関数を登録して、それらを一度にすべて実行できます。登録された各関数はそれぞれ独自のスレッドで実行されるため、ロボットはタッチLEDの点滅や走行など、複数の処理を同時に実行できます。
以下に、利用可能なメソッドとコンストラクタの一覧を示します。
Event– 新しいイベント オブジェクトを作成します。broadcast– イベント オブジェクトに登録されているすべての関数を並列実行するようにトリガーします。broadcast_and_wait– イベント オブジェクトに登録されているすべての関数をトリガーし、それらが完了するまで待機してから処理を続行します。event– オプションで引数を指定して、イベント オブジェクトに関数を登録します。
Create an Event Object#
Event 、別々のスレッドで関数の実行を管理するイベント オブジェクトを作成します。
Usage:
Event()
パラメータ |
説明 |
|---|---|
このコンストラクタにはパラメータがありません。 |
def dash_lines():
# Move the pen up and down
while True:
pen.move(DOWN)
wait(0.5, SECONDS)
pen.move(UP)
wait(0.5, SECONDS)
def main():
# Set the event
move_event = Event()
move_event(dash_lines)
# Draw the dash line while driving forward
move_event.broadcast()
drivetrain.drive_for(FORWARD, 1000, MM)
# VR threads — Do not delete
vr_thread(main)
Broadcast#
broadcast はイベントをトリガーし、登録されているすべての関数を別々のスレッドで起動します。このメソッドは、後続の関数の実行を一時停止しません。
Usage:
my_event.broadcast()
パラメータ |
説明 |
|---|---|
|
以前に作成されたイベントオブジェクトの名前。 |
def dash_lines():
# Move the pen up and down
while True:
pen.move(DOWN)
wait(0.5, SECONDS)
pen.move(UP)
wait(0.5, SECONDS)
def main():
# Set the event
move_event = Event()
move_event(dash_lines)
# Draw the dash line while driving forward
move_event.broadcast()
drivetrain.drive_for(FORWARD, 1000, MM)
# VR threads — Do not delete
vr_thread(main)
Broadcast and wait#
broadcast_and_wait イベントを開始しますが、後続の関数を続行する前に、登録されているすべての関数が終了するまで待機します。
Usage:
my_event.broadcast_and_wait()
パラメータ |
説明 |
|---|---|
|
以前に作成されたイベントオブジェクトの名前。 |
def move_and_turn():
# Drive forward and turn
drivetrain.drive_for(FORWARD, 150, MM)
drivetrain.turn_for(RIGHT, 90, DEGREES)
def main():
# Wait for the event to finish after 3 seconds
move_event = Event()
move_event(move_and_turn)
while True:
if brain.timer_time(SECONDS) > 3:
move_event.broadcast_and_wait()
break
wait(5, MSEC)
brain.print("Movement done.")
# VR threads — Do not delete
vr_thread(main)
Register Functions to an Event#
イベントに関数を登録すると、そのイベントがブロードキャストされたときに、関数は別のスレッドで実行されます。
Usage:
event(callback, args)
パラメータ |
説明 |
|---|---|
|
以前に作成されたイベントオブジェクトの名前。 |
|
イベントがブロードキャストされた際に実行される、事前に定義された関数。 |
def dash_lines():
# Move the pen up and down
while True:
pen.move(DOWN)
wait(0.5, SECONDS)
pen.move(UP)
wait(0.5, SECONDS)
def main():
# Set and call the event and start driving
move_event = Event()
move_event(dash_lines)
move_event.broadcast()
drivetrain.drive(FORWARD)
# VR threads — Do not delete
vr_thread(main)