0

Let's say we have a parent class called Sensor. Mobile robot has a variety of sensors (e.g cam, sonar, laser, GPS, ... etc). Each sensor has its own thread and it provides the Robot with noisy measurements. I would like to simulate this scenario, therefore the code might look like the following

class Robot 
{
   update() 
   {
       mSensor[i]->update();
   }
   Sensor *mSensor;
}

class Sensor
{
   update();
}

class GPS : public Sensor 
{
   Thread mThread();
   update();
}

class CAM : public Sensor 
{
   Thread mThread();
   update();
}

In the main function, basically I need to create a Robot object, therefore

#include "Robot.h"

int main()
{
   Robot robo;
   while( true ){
     robot.update(); 
  }
}

My question is how can I guarantee the threads of Sensors are terminated by only terminating the robo object? Do I have to go through all sensors objects by some kind of loop in parent destructor?

CroCo
  • 5,531
  • 9
  • 56
  • 88
  • Your sample code is a bit too minimal –  Jul 24 '15 at 17:01
  • On Windows at least, if you terminate the process, all threads in that process will get terminated. Though "termination" would better be a graceful shutdown, so when main is about to exit, it should request that all threads to end, and wait for those to gracefully shutdown. You would have to build all of this, both for thread terminate request and response. – Chris O Jul 24 '15 at 17:03
  • I think what you are looking for is "resource acquisition is initialization" idiom. http://stackoverflow.com/questions/395123/raii-and-smart-pointers-in-c – ramana_k Jul 24 '15 at 17:10

1 Answers1

2

First off don't use a Sensor *mSensor; and instead use a std::vector<std::unique_ptr<Sensor>>. Secondly the destructor of each sensor should end the thread. Then when the Robot class is destroyed the vector will be destroyed which will call the destructor off all of the sensors in the vector.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402