According to the C++ 14 standard, non-static member variables are initialised in the order they are declared in a class. The cut down code below relies on this rule to control a thread function.
class foo
{
foo():
keep_going{true},
my_thread(&foo::go,this)
{}
void go()
{
while(keep_going)
check a std::condition_variable and do some work;
}
bool keep_going;
std::thread my_thread;
}
Note that keep_going
is declared before the thread object and should be set to true
by the time the thread enters the go function. This is fine and seems to work OK.
However, this is multithreaded code and it pays to be paranoid so I have two questions:
1 Is it safe to rely on the order of initialisation like this? My real object doesn't make sense without the processing thread so I want to set it going in the constructor.
2 Is it unsafe to give code to others when it relies on relatively obscure things like the order of initialisation?