Skip to main content

VEX code Threads

Example Code to use a Thread

There is an example in vexcode pro, reproduced here:

/*----------------------------------------------------------------------------*/
/*                                                                            */
/*    Module:       main.cpp                                                  */
/*    Author:       VEX                                                       */
/*    Created:      Sun Oct 06 2019                                           */
/*    Description:  This program will run a tasks parallel (at the same time  */
/*                  to main.                                                  */
/*                                                                            */
/*----------------------------------------------------------------------------*/

// ---- START VEXCODE CONFIGURED DEVICES ----
// ---- END VEXCODE CONFIGURED DEVICES ----

#include "vex.h"

using namespace vex;

// myTaskCallback is a callback function that can be registered to a task. In
// this program, it is registered to 'myTask'.
int myTaskCallback() {
  int count = 0;
  while (true) {
    Brain.Screen.setCursor(1, 1);
    Brain.Screen.print("myTaskCallback has iterated %d times", count);
    count++;
    wait(25, msec);
  }
  // A task's callback must return an int, even though the code will never get
  // here. You must return an int here. Tasks can exit, but this one does not.
  return 0;
}

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();

  // Declare and assign myTask's callback to 'myTaskCallback'.
  // The task will start as soon as this command is called.
  task myTask = task(myTaskCallback);

  // Print from the main task to show that it is running at the same time as
  // 'myTaskCallback'.
  int count = 0;
  while (true) {
    Brain.Screen.setCursor(2, 1);
    Brain.Screen.print("main has iterated %d times", count);
    count++;
    wait(25, msec);
  }
}

When do These Threads Run and When do They Stop

Here is a note by Pearman on this topic.

The summary of this is once a thread is started it stays running until you stop it.  So if you start something in Auton mode it will stay running in Driver Mode.  This may be what you want but it may not be what you want.

For most of our applications we should just stop all threads when the robot moves from mode to mode, so whenever the robot is disabled all threads stop.  

This can be done by putting this line of code in main:

Competition.bStopAllTasksBetweenModes = true;

All your tasks running will stop. The only problem with this is if you have some tasks that you would like to keep running. You would have to launch them again in the next mode.