Skip to content

Davis High Robotics Association.

Davis High School Extra-Curricular Robotics Club Wiki and Website. 2x World Champion, Davis High Robotics is worth contributing to today.

main.cpp

void start()
  {
    // Require that T inherits from std::enable_shared_from_this<T> to
    // ensure that we can get a weak pointer reference to the underlying
    // data for safe multithreading
    static_assert(
        std::is_base_of_v<std::enable_shared_from_this<T>, T>,
        "Task<T> requires T to inherit from"
        " std::enable_shared_from_this<T>");

    // Check that the thread is valid before starting (IE, Not default
    // constructed)
    if (validThread)
    {
      // Get a weak pointer reference to the underlying data for the task
      std::weak_ptr<T> self = data->weak_from_this();

      // Start the PROS task with a lambda that captures the weak pointer
      task = pros::Task(
          [&]() {
            bool valid = true;

            // While the thread is marked as valid
            while (valid)
            {
              if (auto s = self.lock())
              {
                valid = validThread;  // Check if the thread is still valid
                taskFunction();       // Execute the task function
              }
              else
              {
                valid = false;
              }  // If the weak pointer can't be locked, the underlying
                 // data has been destroyed, so exit the thread cleanly

              // Delay to not hog the CPU, and to allow other tasks to run.
              pros::delay(delayMs);
            }
          },
          taskName.c_str());
    }
  }