GOPHERSPACE.DE - P H O X Y
gophering on gopher.linkerror.com
It's quite common, especially when you have to interact with C libraries, to 
have to call a bit of code that is not thread-safe in your main thread, before
you can use the rest of the functions provided in a library.

For instance, curl and sqlite have specific initialization and setup functions
that are not thread-safe (and often are required to be called for 
thread-safe setup)

If you're providing an interface to a library like that, it would kind of suck
to have to rely on the caller to do the right thing, and only call setup from
the main thread.

I mean, yeah, you could put init stuff in your constructor, but you can't
guarantee that the user will construct your class from the main thread, nor
can you guarantee that the class won't be constructed in multiple threads at
once.

Modern c++ lets you do a neat little trick (although it's kind of ugly) :
you can automatically run your setup code from the main thread, exactly, 
and only, once. This can be accomplished by using std::call_once in 
combination with a proxy variable like so:

    // ( Imagine you have a Foo class with member Setup() that needed
    //   to be called in the main thread )
    //
    // in the Foo.cpp implementation you would do:

    static std::once_flag s_fooInitializedFlag;
    static bool setupFoo()
    {
        auto doFooSetup = []() { Foo::Setup(); };
        std::call_once(s_fooInitializedFlag, doFooSetup);
        return true;
    }

    // Proxy variable
    static const auto s_fooSetupDummy = setupFoo();

    // Actually class Setup() member implementation
    void Foo::Setup()
    {
        // this doesn't do anything but avoids a compiler warning about
// s_fooSetupDummy being unused.
        (void)s_fooSetupDummy;

        // init magic goes here

    }