이벤트#

소개#

이벤트는 이벤트 객체를 사용하여 함수를 병렬로 실행할 수 있도록 해줍니다. 함수나 스레드를 순차적으로 호출하는 대신, 이벤트를 통해 함수를 등록하고 한 번에 모두 실행할 수 있습니다. 등록된 각 함수는 자체 스레드에서 실행되므로 로봇은 터치 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()

매개변수

설명

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 and wait#

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

Usage:
my_event.broadcast_and_wait()

매개변수

설명

event

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

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)

매개변수

설명

event

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

callback

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

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)