執行緒#

介紹#

執行緒允許機器人在同一程式中同時執行多個任務。它們實現了多任務處理,使機器人能夠同時執行獨立的動作。

類別建構函數#

1 — 建立並啟動一個帶有函數的新執行緒。

thread( void (* callback)(void) );

2 — 建立並啟動一個新線程,該線程使用一個接受參數的函數。

thread( int (* callback)(void *), void *arg );

類別析構函數#

銷毀 thread 物件並釋放相關資源。

~thread();

參數#

範圍

類型

描述

callback

void (*)(void)

一個預先定義的函數,將在新線程中運行。

callback

int (*)(void *)

一個預先定義的函數,接受一個 void 指標參數,並將在新執行緒中執行。

arg

void *

傳遞給回呼函數的空指標。

筆記#

  • 函數必須在呼叫之前定義。

  • 建立線程時,您可以為其命名,以便在專案中單獨管理它。

  • 一旦使用 interrupt()停止線程,就無法重新啟動。要再次運行它,必須建立一個新執行緒。

例子#

定義函數(在 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);
  }
}

在 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);
}

定義函數(在 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);
}

在 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 – 手動停止線程,可用於停止後台行為。

interrupt#

手動停止線程,這在不再需要某個任務或程式需要重置線程時非常有用。

Available Functions
void interrupt();

Parameters

此函數沒有參數。

Return Values

此函數不傳回值。

Notes
  • 線程一旦停止,就無法重新啟動。要再次運行它,必須使用 thread 建立一個新執行緒。

  • 當不再需要某個任務,或程式需要重置或重新分配執行緒時,這非常有用。

Examples

定義函數(在 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);
  }
}

在 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();
}