Boost logo

Boost Users :

Subject: Re: [Boost-users] What is the best idiom for using call_once ?
From: John M. Dlugosz (mpbecey7gu_at_[hidden])
Date: 2012-11-18 06:42:45


Date: Sat, 17 Nov 2012 13:51:48 +0100 From: "Vicente J. Botet Escriba"
<vicente.botet_at_[hidden]>
> Hi, your code suffers from the problem you try to avoid "But we all know this is not
> thread safe, at least for the first call" at least in c++98 as you are using static
> variables.
Actually, my post described the circumstances under which it does in fact work: when
VarType has a built-in type that is initialized before program execution, or on C++11 with
a constexpr constructor.

> here they are some pointers that while not responding exactly to your
> question them could help you.
>
> http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-6-double-checked-locking.html
Interesting, the post gets it wrong. A unique_ptr has a constructor (in C++03) so still
has the problem. Or, maybe the article is just not clear on how it is to be used: if you
must initialize an instance of lazy_init (to the null pointer internally) _before_
multiple threads ask it to be "initialized", that just pushes the problem back to the
earlier step. I can see the usefulness though, if you just want to put off the expensive
"real" initialization until needed, but can arrange the pre-initialization to be done
for-sure earlier.

>
> http://stackoverflow.com/questions/12302057/c11-safe-double-checked-locking-for-lazy-initialization-possible
This points out that under C++11 rules, static locals are thread safe for the first-time
initialization. That explains why there is no fancy construct for doing so; it's just
there! Nice. Or it will be, some day. I looked at the code generated by Microsoft VS2010
and it does not give this feature, alas.

It does tell me though that a compatibility construct like I'm looking for ought to expand
into a plain static local for compilers that do work that way; just let the compiler do
it. All the more reason to abstract the issue for current uses!

—John


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net