이벤트#

소개#

이벤트를 사용하면 함수를 병렬로 실행할 수 있습니다. 함수를 순차적으로 호출하는 대신, 여러 함수를 이벤트에 등록하고 한 번에 모두 실행할 수 있습니다. 등록된 각 함수는 자체 스레드에서 실행되므로 로봇이 주행 중 화면에 값을 표시하는 것과 같이 여러 작업을 동시에 수행할 수 있습니다.

이벤트를 생성하고 사용하려면 다음 단계를 순서대로 따르십시오.

  1. Event를 사용하여 이벤트를 생성합니다.

  2. 함수를 인수로 사용하여 Event 객체를 호출하여 event 이 브로드캐스트될 때 트리거되는 함수를 등록합니다.

  3. Broadcast an Event:

    • broadcast – 이벤트 객체에 등록된 모든 함수가 동시에 실행되도록 트리거합니다.

    • broadcast_and_wait – 이벤트 객체에 등록된 모든 함수를 트리거하고 계속하기 전에 함수가 완료될 때까지 기다립니다.

이벤트 생성#

Event 별도의 스레드에서 함수 실행을 관리하는 이벤트 객체를 생성합니다.

Usage:
Event()

매개변수

설명

이 생성자에는 매개변수가 없습니다.

def move_square():
    for index in range(4):
        drivetrain.drive_for(FORWARD, 150)
        drivetrain.turn_for(RIGHT, 90)

# *** Creating the move_event Event ***
move_event = Event()

# Register move_square to move_event
move_event(move_square)

# Call all functions registered to move_event
move_event.broadcast()

이벤트에 함수 등록하기#

함수를 이벤트에 등록하면 해당 이벤트가 브로드캐스트될 때 별도의 스레드에서 실행됩니다.

Usage:
event(callback, args)

매개변수

설명

event

이전에 생성된 이벤트 객체의 이름입니다.

callback

이벤트가 브로드캐스트될 때 실행되도록 미리 정의된 함수입니다.

args

선택 사항입니다. 콜백 함수에 전달할 인수의 튜플입니다.

def move_square():
    for index in range(4):
        drivetrain.drive_for(FORWARD, 150)
        drivetrain.turn_for(RIGHT, 90)

# Creating the move_event Event
move_event = Event()

# *** Register move_square to move_event ***
move_event(move_square)

# Call all functions registered to move_event
move_event.broadcast()

이벤트 방송하기#

broadcast#

broadcast 이벤트를 발생시켜 등록된 모든 함수를 별도의 스레드에서 시작합니다. 이 메서드는 이후 함수의 실행을 일시 중지하지 않습니다.

Usage:
event.broadcast()

매개변수

설명

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)

move_event = Event()
move_event(move_square)
# Broadcasting the move_event Event
move_event.broadcast()
optical_sensor.set_light_power(100, PERCENT)

broadcast_and_wait#

broadcast_and_wait 이벤트를 시작하지만 등록된 모든 함수가 완료될 때까지 기다린 후 후속 함수를 진행합니다.

Usage:
event.broadcast_and_wait()

매개변수

설명

event

이전에 생성된 이벤트 객체의 이름입니다.

def move_square():
    for index in range(4):
        drivetrain.drive_for(FORWARD, 150)
        drivetrain.turn_for(RIGHT, 90)

# 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()
optical_sensor.set_light_power(100, PERCENT)