class ScopeFeeder
{
public:
ScopeFeeder() :
loop_thread__( [this](){ loop(); } )
{}
~ScopeFeeder()
{
stop_ = true;
loop_thread__.join();
}
...
private:
std::thread loop_thread__;
bool stop_ = false;
void loop()
{
cout << "loop starting ...\n";
while( !stop_ )
{
cout << "loop ...\n";
...
}
cout << "loop end ...\n";
}
};
sc
r
o
l
l
d
o
w
n
stop_ can be true when loop() is running obviously. And it can be as initilizaton order matters in here and stop_ has to be initialized first. If you put stop_ in front of loop_thread_, then stop_ is not undefined anymore and loop() will run happily ever after.
class ScopeFeeder
{
...
private:
bool stop_ = false; // stop_ first.
std::thread loop_thread__;
...
};