イベント#
導入#
イベントを使用すると、関数を並列実行できます。関数を順番に呼び出す代わりに、複数の関数をイベントに登録して、それらを一度にすべて実行できます。登録された各関数はそれぞれ独自のスレッドで実行されるため、ロボットは走行中に画面に値を表示するなど、複数のタスクを同時に実行できます。
イベントを作成して使用するには、以下の手順を順番に実行してください。
Eventを使用してイベントを作成します。関数を引数として
Eventオブジェクト を呼び出すことにより、eventがブロードキャストされたときにトリガーされる関数を登録します。Broadcast an
Event:broadcast– イベント オブジェクトに登録されているすべての関数を同時に実行するようにトリガーします。broadcast_and_wait– イベント オブジェクトに登録されているすべての関数をトリガーし、それらが完了するまで待機してから処理を続行します。
イベントを作成する#
Event 、別々のスレッドで関数の実行を管理するイベント オブジェクトを作成します。
Usage:
Event()
パラメータ |
説明 |
|---|---|
このコンストラクタにはパラメータがありません。 |
# Build Used: Super Code Base 2.0
def move_square():
for index in range(4):
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def main():
# Creating the move_event Event
move_event = Event()
move_event(move_square)
move_event.broadcast()
bumper.set_color(GREEN)
# Start threads — Do not delete
start_thread(main)
イベントに関数を登録する#
イベントに関数を登録すると、そのイベントがブロードキャストされたときに、関数は別のスレッドで実行されます。
Usage:
event(callback, args)
パラメータ |
説明 |
|---|---|
|
以前に作成されたイベントオブジェクトの名前。 |
|
イベントがブロードキャストされた際に実行される、事前に定義された関数。 |
|
Optional. A tuple of arguments to pass to the callback function. |
# Build Used: Super Code Base 2.0
def move_square():
for index in range(4):
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def main():
move_event = Event()
# Register the move_square function to the move_event Event
move_event(move_square)
move_event.broadcast()
bumper.set_color(GREEN)
# Start threads — Do not delete
start_thread(main)
イベントを放送する#
broadcast#
broadcast はイベントをトリガーし、登録されているすべての関数を別々のスレッドで起動します。このメソッドは、後続のコードの実行を一時停止しません。
Usage:
event.broadcast()
パラメータ |
説明 |
|---|---|
|
以前に作成されたイベントオブジェクトの名前。 |
# Build Used: Super Code Base 2.0
def move_square():
for index in range(4):
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def main():
move_event = Event()
move_event(move_square)
# Broadcasting the move_event Event
move_event.broadcast()
bumper.set_color(GREEN)
# Start threads — Do not delete
start_thread(main)
broadcast_and_wait#
broadcast_and_wait イベントを開始しますが、後続の関数を続行する前に、登録されているすべての関数が終了するまで待機します。
Usage:
event.broadcast_and_wait()
パラメータ |
説明 |
|---|---|
|
以前に作成されたイベントオブジェクトの名前。 |
# Build Used: Super Code Base 2.0
def move_square():
for index in range(4):
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def main():
# Set up and call the move_square event
move_event = Event()
move_event(move_square)
# Broadcast the move_event Event and wait
move_event.broadcast_and_wait()
bumper.set_color(GREEN)
# Start threads — Do not delete
start_thread(main)