如何通过仅终止子对象的父对象来退出子对象的独立线程

how to quit an independent thread of a child object by only terminating its parent object

本文关键字:对象 退出 独立 线程 何通过 终止      更新时间:2023-10-16

假设我们有一个父类Sensor。移动机器人有各种传感器(如凸轮、声纳、激光、GPS等)。等等)。每个传感器都有自己的线程,它为机器人提供噪声测量。我想模拟这个场景,因此代码可能如下所示

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();
}
在main函数中,基本上我需要创建一个Robot对象,因此
#include "Robot.h"
int main()
{
   Robot robo;
   while( true ){
     robot.update(); 
  }
}

我的问题是如何保证传感器的线程只终止机器人对象?我需要在父析构函数中通过某种循环遍历所有传感器对象吗?

首先不要使用Sensor *mSensor;,而是使用std::vector<std::unique_ptr<Sensor>>。其次,每个传感器的析构函数都应该结束线程。然后,当Robot类被销毁时,向量将被销毁,这将调用析构函数关闭向量中的所有传感器。