线程#
介绍#
线程允许机器人在同一程序中同时运行多个任务。它们实现了多任务处理,使机器人能够同时执行独立的动作。
注意: 必须Functions.md#defining-and-calling-functions定义一个函数才能在线程中使用它。
构造函数——创建并启动新线程。
thread– Starts a new thread that runs the specified function in parallel with the main program.
操作 – 控制正在运行的线程。
interrupt– Stops a thread manually, useful for halting background behavior.
构造函数#
thread#
thread creates and starts a thread. When you create a thread, you can name it to manage it individually in your project.
用法:
thread myThread = thread(myFunction);
参数 |
描述 |
|---|---|
|
(可选)新帖子的名称。 |
|
先前定义的函数的名称。 |
注意: 函数必须在调用之前定义**。
// Drive forward while blinking screen
void blinkScreen() {
while (true) {
Brain.Screen.clearScreen(red);
wait(0.5, seconds);
Brain.Screen.clearScreen();
wait(0.5, seconds);
}
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
thread blinkScreenThread = thread(blinkScreen);
Drivetrain.drive(forward);
}
// Run multiple threads simultaneously
// Turn right, blink screen at once
void blinkScreen() {
while (true) {
Brain.Screen.clearScreen(red);
wait(0.5, seconds);
Brain.Screen.clearScreen();
wait(0.5, seconds);
}
}
void turning() {
Drivetrain.turn(right);
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
thread blinkScreenThread = thread(blinkScreen);
thread turningThread = thread(turning);
}
行动#
interrupt#
interrupt stops a thread manually, which is useful when a task is no longer needed or when a program needs to reset or reassign threads. Once a thread is stopped, it cannot be restarted. To run it again, you must create a new thread using thread.
Usage:
myThread.interrupt();
参数 |
描述 |
|---|---|
|
A previously started thread object. This is the name assigned when the thread was created using |
// Loop through red and green
void colorLoop() {
while (true) {
Brain.Screen.drawRectangle(0, 120, 480, 120, red);
wait(0.5, seconds);
Brain.Screen.drawRectangle(0, 120, 480, 120, green);
wait(0.5, seconds);
}
}
// Display the current heading
void displayHeading() {
Brain.Screen.setFont(prop60);
while (true) {
Brain.Screen.clearLine(1);
Brain.Screen.setCursor(1, 1);
Brain.Screen.print(
"Heading: %.1f",
DrivetrainInertial.heading(degrees)
);
wait(50, msec);
}
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Turn right, change screen color, and display heading at once
thread colorThread = thread(colorLoop);
thread displayHeadingThread = thread(displayHeading);
Drivetrain.turn(right);
wait(2, seconds);
// Stop the flashing colors
colorThread.interrupt();
}