hogliux/semimap

A quick question about the init_flag.

Closed this issue · 2 comments

Hey I just watched your cppcon talk, great job btw. I was wondering if maybe the init_flag can be avoided. From what I understood you basically need to execute the add to the runtime map only when the static is initted. I guess you can use the iele(immediately executed lambda expression) trick. Some pseudo code:

template <typename Value>
Value& get_internal(const Key& key)
{
    static Value value = [&key]()
    {
        runtime_map[key] = &value;
        return Value{};
    }();

    return value;
}

Could this remove the need for the init_flag or am I missing something?

Yes, but this would re-introduce the lock-guard via the local static you introduced. Internally, a lock guard is a compiler-generated init_flag plus a locking mechanism which is slower than just an init_flag.

To demonstrate this, I've put your code into compiler explorer:

https://gcc.godbolt.org/z/AfxDz2

You can see on line 282 of the assembly, how an lock guard's init_flag (called "guard variable for init") is still being checked. A bit further down, __cxa_guard_acquire is called which will then lock out other threads.

I talk about this a bit on slide 34 of my talk: https://youtu.be/qNAbGpV1ZkU?t=880

Hmm i guess you are right. Thanks. :)