https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93610

            Bug ID: 93610
           Summary: std::call_once not working as expected when the
                    invocated function thwows an exception.
           Product: gcc
           Version: 10.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: mariogalindoq at hotmail dot com
  Target Milestone: ---

cppreference.com (https://en.cppreference.com/w/cpp/thread/call_once) says:
If that invocation throws an exception, it is propagated to the caller of
call_once, and the flag is not flipped so that another call will be attempted
(such call to call_once is known as exceptional).
This is not working with gcc but with clang.

The example that appears in cppreference do not run with gcc. In particular:

#include <iostream>
#include <thread>
#include <mutex>

std::once_flag flag2;

void may_throw_function(bool do_throw)
{
  if (do_throw) {
    std::cout << "throw: call_once will retry\n"; // this may appear more than
once
    throw std::exception();
  }
  std::cout << "Didn't throw, call_once will not attempt again\n"; //
guaranteed once
}

void do_once(bool do_throw)
{
  try {
    std::call_once(flag2, may_throw_function, do_throw);
  }
  catch (...) {
  }
}

int main()
{ 
    std::thread t1(do_once, true);
    std::thread t2(do_once, true);
    std::thread t3(do_once, false);
    std::thread t4(do_once, true);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}

Reply via email to