问题
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