In my C++ code I’m keeping a pointer to an object
which should be created lazily, i.e., created only upon request.
I have following code, which is clearly not thread-safe.
LAZY* get_lazy()
{
if (0 == _lazy)
_lazy = create_lazy();
return _lazy;
}
I wonder what kind of synchronization should I use here?
I know Boost.thread provides supports for one-time initialization.
But I’m hoping that there is a simple solution using TBB + C++ only.
I should also note that…
- I cannot create
_lazyas a static object (I actually want to keep an unbounded array of such lazily created objects) - Such
LAZYobjects cannot be over-allocated (creation is very expensive)
You need a local mutex (tbb::mutex), to be sure you create your lazy object only once.