이벤트#

소개#

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

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

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

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

  3. Broadcast an Event:

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

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

이벤트 생성#

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

Usage:
Event()

매개변수

설명

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

# Blink the screen while moving forward
# Create move_event as an Event object
move_event = Event()

def blink_screen():
    while True:
        brain.screen.clear_screen(Color.RED)
        wait(0.5, SECONDS)
        brain.screen.clear_screen()
        wait(0.5, SECONDS)

move_event(blink_screen)
move_event.broadcast()
drivetrain.drive(FORWARD)

이벤트에 함수 등록하기#

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

Usage:
event(callback, args)

매개변수

설명

event

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

callback

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

args

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

# Blink the screen while turning
move_event = Event()

def blink_screen():
    while True:
        brain.screen.clear_screen(Color.RED)
        wait(0.5, SECONDS)
        brain.screen.clear_screen()
        wait(0.5, SECONDS)

def turning():
    drivetrain.turn(RIGHT)

# Register multiple functions to the Event object
move_event(blink_screen)
move_event(turning)

move_event.broadcast()

# Move in a specified direction
move_event = Event()

def move_distance(movement_angle):
    drivetrain.turn_for(RIGHT, movement_angle, DEGREES)
    drivetrain.drive_for(FORWARD, 100, MM)

# Change the parameter to modify how the robot moves
move_event(move_distance, (180,))
move_event.broadcast()

이벤트 방송하기#

broadcast#

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

Usage:
event.broadcast()

매개변수

설명

event

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

# Blink the screen while moving forward
# Create move_event as an Event object
move_event = Event()

def blink_screen():
    while True:
        brain.screen.clear_screen(Color.RED)
        wait(0.5, SECONDS)
        brain.screen.clear_screen()
        wait(0.5, SECONDS)

move_event(blink_screen)
move_event.broadcast()
drivetrain.drive(FORWARD)

broadcast_and_wait#

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

Usage:
event.broadcast_and_wait()

매개변수

설명

event

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

# Move after the screen is pressed
move_event = Event()

def move_and_turn():
    drivetrain.drive_for(FORWARD, 150, MM)
    drivetrain.turn_for(RIGHT, 90)

move_event(move_and_turn)

while True:
    if brain.buttonCheck.pressing():
        move_event.broadcast_and_wait()
        break
brain.screen.print("Movement done.")