Calling `f()` once regardless of exceptions

2019-09-17 09:26发布

My understanding may be incorrect but, reading the documentation for call_once, it appears that if multiple threads are calling it simultaneously with the same once_flag and the first thread throws an exception, one of the other threads will have its callable called (and so forth until one callable returns without throwing).

My question is, if I have multiple thread all the with the same callable and I want the callable to be called truly once regardless of an exception and I want to know about the exception, do I have no choice but to do this:

void call_really_just_once()
{
    std::exception_ptr e;

    std::call_once(some_once_flag_, [&]
    {
        try
        {
            may_throw();
        }
        catch(...)
        {
            e = std::current_exception();
        }
    });

    if(e)
    {
        std::rethrow_exception(e);
    }
}

标签: c++ c++11 mutex
0条回答
登录 后发表回答