0

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);
    }
}
Eliad
  • 894
  • 6
  • 20
screwnut
  • 1,367
  • 7
  • 26
  • http://coliru.stacked-crooked.com/a/a11b0f53fe80725b – Mooing Duck Aug 19 '14 at 00:28
  • @Mooing Duck, How so? The callable itself will never throw and once it returns `some_once_flag_` will be set to "don't run again". – screwnut Aug 19 '14 at 00:39
  • oh, now I see it. Yeah. All threads block though, until then – Mooing Duck Aug 19 '14 at 00:52
  • `static bool once = (may_throw(),true);`, though neat, behaves exactly as `call_once` – Mooing Duck Aug 19 '14 at 00:53
  • @Mooing Duck. You're right about threads blocking. This made me realize that, in the context where I will be using this, I do have the following additional requirement: when you return from `call_really_just_once`, the callable _must_ have been called. i.e. it has to behave just like `call_once` in that regard. I believe my code above fulfills that extra requirement. – screwnut Aug 19 '14 at 01:19
  • Oh, in that case your code looks ok, just uncommented – Mooing Duck Aug 19 '14 at 01:47
  • Your question might be a better fit for http://codereview.stackexchange.com/ – Praetorian Aug 19 '14 at 03:02

0 Answers0