Thread: Tasks in C++
View Single Post
  #2   Spotlight this post!  
Unread 02-04-2016, 14:34
AustinSchuh AustinSchuh is offline
Registered User
FRC #0971 (Spartan Robotics) #254 (The Cheesy Poofs)
Team Role: Engineer
 
Join Date: Feb 2005
Rookie Year: 1999
Location: Los Altos, CA
Posts: 800
AustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond repute
Re: Tasks in C++

Quote:
Originally Posted by taichichuan View Post
Can you provide a simple example of using ::std::thread that's compatible with the roborio?

TIA,

Mike
From our code:

Code:
-- snip --
    ::frc971::wpilib::GyroSender gyro_sender;
    ::std::thread gyro_thread(::std::ref(gyro_sender));

    //  Main loop here

    // Now cleanup
    gyro_sender.Quit();
    gyro_thread.join();

-- snip --

// Handles reading the gyro over SPI and sending out angles on a queue.
//
// This is designed to be passed into ::std::thread's constructor so it will run
// as a separate thread.
class GyroSender {
 public:
  GyroSender();

  // For ::std::thread to call.
  //
  // Initializes the gyro and then loops until Quit() is called taking readings.
  void operator()();

  void Quit() { run_ = false; }

 private:

  // Readings per second.
  static const int kReadingRate = 200;

  GyroInterface gyro_;

  ::std::atomic<bool> run_{true};
};
There are a bunch of different variants for how to create the ::std::function that ::std::thread takes for a constructor. A simpler version would be to define a void foo(){} and pass that in. You can also use ::std::bind to call arbitrary functions with arbitrary arguments.
Reply With Quote