Ниже приведен мой код:
Код: Выделить всё
// Base.h
#include
#include
#include
#include
#include
#include
class Base
{
private:
protected:
std::thread routineThread;
uint16_t state = 0;
bool isRoutineRunning = false;
void routine();
public:
Base();
~Base();
void startRoutine();
void stopRoutine();
virtual void outputState();
};
// Base.cpp
#include "Base.h"
#include
#include
Base::Base()
: routineThread()
{
}
Base::~Base()
{
isRoutineRunning = false;
if (routineThread.joinable())
{
routineThread.join();
}
}
void Base::outputState()
{
printf("%ld: base class object state = %d\r\n", time(nullptr), state);
}
void Base::routine()
{
while (true)
{
outputState();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void Base::startRoutine()
{
printf("%ld: tried to start routine thread\r\n", time(nullptr));
if (!isRoutineRunning)
{
routineThread = std::thread(&Base::routine, this);
isRoutineRunning = true;
printf("%ld: routine thread started\r\n", time(nullptr));
}
}
void Base::stopRoutine()
{
if (isRoutineRunning)
{
isRoutineRunning = false;
if (routineThread.joinable())
{
routineThread.join();
}
}
}
// Derived.h
#include "Base.h"
class Derived : public Base
{
private:
protected:
public:
Derived(/* args */);
~Derived();
void init();
void outputState() override;
};
// Derived.cpp
#include "Derived.h"
#include
#include
Derived::Derived()
{
}
Derived::~Derived()
{
}
void Derived::init()
{
state = 1;
}
void Derived::outputState()
{
printf("%ld: derived class ojbect state = %d\r\n", time(nullptr), state);
}
// main.cpp
#include "./classes/Base.h"
#include "./classes/Derived.h"
int main()
{
Derived derived;
derived.init();
derived.outputState(); This line seems to work as expected if the following line is commented out
derived.startRoutine();
return 1;
}
Код: Выделить всё
1761776592: derived class ojbect state = 1 // This is expected
1761776592: tried to start routine thread
1761776592: routine thread started
// The following output are from virtual function in Parent class while state variable is from Child class
1761776592: base class object state = 1
1761776593: base class object state = 1
1761776594: base class object state = 1
1761776595: base class object state = 1
1761776596: base class object state = 1
Есть ли способ заставить поток вызывать рутинную функцию в дочернем классе?>
Подробнее здесь: https://stackoverflow.com/questions/798 ... class-that
Мобильная версия