jeudi 20 avril 2017

The callable function called by std::call_once will hang if it tries to call std::call_once on the same std::once_flag

I ran into a bug caused by this behaviour:

#include <mutex>

std::once_flag onceFlag;

void get() {
    std::call_once(onceFlag, [](){ get(); });
}

int main(int argc, char* argv[]) {
    get();
    return 0;
}

Another way of putting it would be:

#include <mutex>

std::once_flag onceFlag;

int main(int argc, char* argv[]) {
    std::call_once(onceFlag,
        [](){
            std::call_once(onceFlag,
                [](){}
            );
        }
    );

    return 0;
}

According to what I read here at cppreference (http://ift.tt/2lwBPvT) this is to be expected, as the first call to std::call_once hasn't finished executing:

No invocation in the group returns before the above-mentioned execution of the selected function is completed successfully, that is, doesn't exit via an exception.

Why is the above a requirement? Couldn't the once_flag be set before the function is called, and reset if an exception is thrown?

Aucun commentaire:

Enregistrer un commentaire