Calling `f()` once regardless of exceptions

余生颓废 提交于 2019-12-13 02:56:51

问题


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);
    }
}

来源:https://stackoverflow.com/questions/25373888/calling-f-once-regardless-of-exceptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!