Trapos#

Introducción#

Los subprocesos permiten que un robot ejecute múltiples tareas simultáneamente dentro del mismo programa. Facilitan la multitarea, permitiendo que el robot realice acciones independientes simultáneamente.

Nota: Debes primero definir una función para usarla con un hilo.

Constructor – Crea e inicia nuevos hilos.

  • thread – Starts a new thread that runs the specified function in parallel with the main program.

Acción – Controlar hilos en ejecución.

  • interrupt – Stops a thread manually, useful for halting background behavior.

Constructor#

thread#

thread creates and starts a thread. When you create a thread, you can name it to manage it individually in your project.

Uso:

thread myThread = thread(myFunction);

Parámetros

Descripción

myThread

Opcional. Un nombre para el nuevo hilo.

myFunction

El nombre de una función definida previamente.

Nota: Una función siempre debe definirse antes de ser llamada.

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

Acción#

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

Parámetros

Descripción

myThread

A previously started thread object. This is the name assigned when the thread was created using thread.

// Run multiple threads simultaneously
// Turn right, play a sound and display heading at once
// Stop playing sounds after 2 seconds
void sound() {
  while (true) {
    Brain.playSound(alarm);
    wait(0.5, seconds);
  }
}

void displayHeading() {
  while (true) {
    Brain.Screen.clearScreen();
    Brain.Screen.setCursor(1, 1);
    Brain.Screen.print("Heading: %.1f", BrainInertial.orientation(yaw, degrees));
    wait(50, msec);
  }
}

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Begin project code
  thread soundThread = thread(sound);     
  thread displayHeadingThread = thread(displayHeading);
  Drivetrain.turn(right);

  wait(2, seconds);
  soundThread.interrupt();
}