In a code review today, I stumbled across the following bit of code (slightly modified for posting):
while (!initialized)
{
// The thread can start before the constructor has finished initializing the object.
// Can lead to strange behavior.
continue;
}
This is the first few lines of code that runs in a new thread. In another thread, once initialization is complete, it sets initialized to true.
I know that the optimizer could turn this into an infinite loop, but what's the best way to avoid that?
volatile- considered harmful- calling an
isInitialized()function instead of using the variable directly - would this guarantee a memory barrier? What if the function was declaredinline?
Are there other options?
Edit:
Should have mentioned this sooner, but this is portable code that needs to run on Windows, Linux, Solaris, etc. We use mostly use Boost.Thread for our portable threading library.
exit_nowflag, so you'd wantstd::atomic<bool>with at leastmemory_order_acquire.mo_relaxedwould not be sufficient here, the way it is for anexit_nowflag. Only noticed the difference after I'd closed it. From the title, people probably aren't going to be looking at this for other ways to solve the initialization problem, though (other than spin-wait).