Task 執行緒控制
有些時候,需要同時有多件事一起進行。PROS 的 Task 可以把一部分的程式放到背景執行,達成這個目的。
基本用法
void task_function() {
// whatever you want to run in background
}
pros::Task task(task_function);
這讓我們可以讓機器移動的同時計算機器位置(詳情見 Odometry)
void odometry_loop() {
while (true) {
RobotPosition position = get_position();
pros::delay(10);
}
}
pros::Task odometry(odometry_loop);
⚠️注意:在背景執行的無限迴圈必須有delay。
Task 執行控制
我們可以用 pros::Task 內建的 function 暫停、繼續、或刪除 Task
pros::Task task(task_function);
task.remove(); // delete task
tast.suspend(); // pause task
task.resume(); // resume task
Task notification
Task notification 是一種 Task function 與外界溝通的一個管道,可以由外部直接發送通知給背景執行的 task function。
利用Task notification,可以有效解決Task在Driver control繼續跑並造成控制上的問題。
// modified from https://pros.cs.purdue.edu/v5/tutorials/topical/notifications.html?highlight=task%20remove#ending-tasks-cleanly
pros::Task drive_task;
void autonomous() {
drive_task = pros::Task{ [] {
pros::Motor left_motor{ LEFT_MOTOR_PORT };
pros::Motor right_motor{ RIGHT_MOTOR_PORT };
// while the notification value remains zero for more than 20 ms
while (!pros::Task::notify_take(true, 20)) {
left_motor.move(127);
right_motor.move(127);
}
// add any cleanup code if neccesary
} };
while (true) {
pros::delay(20);
}
}
void opcontrol() {
// send a signal to the drive task so we can operate the robot manually now
drive_task.notify();
pros::Controller master{ pros::E_CONTROLLER_MASTER };
pros::Motor left_motor{ LEFT_MOTOR_PORT };
pros::Motor right_motor{ RIGHT_MOTOR_PORT };
while (true) {
left_motor.move(master.get_analog(pros::E_CONTROLLER_ANALOG_LEFT_Y));
right_motor.move(master.get_analog(pros::E_CONTROLLER_ANALOG_RIGHT_Y));
pros::delay(20);
}
}
PROS Multitasking tutorial: https://pros.cs.purdue.edu/v5/tutorials/topical/multitasking.html?highlight=task
PROS Multitasking extended API: https://pros.cs.purdue.edu/v5/extended/multitasking.html?highlight=task
Last updated