线程#
介绍#
线程允许机器人在同一程序中同时运行多个任务。它们实现了多任务处理,使机器人能够同时执行独立的动作。
类构造函数#
1 — 创建并启动一个带有函数的新线程。
thread( void (* callback)(void) );
2 — 创建并启动一个新线程,该线程使用一个接受参数的函数。
thread( int (* callback)(void *), void *arg );
类析构函数#
Destroys the thread object and releases associated resources.
~thread();
参数#
范围 |
类型 |
描述 |
|---|---|---|
|
|
一个预先定义的函数,将在新线程中运行。 |
|
|
一个预先定义的函数,接受一个 void 指针参数,并将在新线程中运行。 |
|
|
传递给回调函数的空指针。 |
笔记#
函数必须在调用之前定义。
创建线程时,您可以为其命名,以便在项目中单独管理它。
Once a thread is stopped using
interrupt(), it cannot be restarted. To run it again, you must create a new thread.
例子#
Define the function (outside of
int main())// Drive forward while blinking screen void blinkScreen() { while (true) { Brain.Screen.clearScreen(red); wait(0.5, seconds); Brain.Screen.clearScreen(); wait(0.5, seconds); } }Register the thread inside
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Begin project code thread blinkScreenThread = thread(blinkScreen); Drivetrain.drive(forward); }
Define the function (outside of
int main())// 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); }Register the thread inside
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Begin project code thread blinkScreenThread = thread(blinkScreen); thread turningThread = thread(turning); }
成员功能#
线程类包含以下成员函数:
interrupt– Stops a thread manually, useful for halting background behavior.
interrupt#
手动停止线程,这在不再需要某个任务或程序需要重置或重新分配线程时非常有用。
Available Functionsvoid interrupt();
此函数没有参数。
Return Values此函数不返回值。
Notes线程一旦停止,就无法重新启动。要再次运行它,必须使用
thread创建一个新线程。当不再需要某个任务,或者程序需要重置或重新分配线程时,这非常有用。
Define the function (outside of
int main())// 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); } }Register the thread inside
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ 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(); }