Bug 25512

Summary: std::call_once not working as expected when the invocated function throws an exception.
Product: glibc Reporter: Mario Galindo <mariogalindoq>
Component: libcAssignee: Not yet assigned to anyone <unassigned>
Status: RESOLVED DUPLICATE    
Severity: normal CC: drepper.fsp, fweimer, mariogalindoq
Priority: P2 Flags: fweimer: security-
Version: unspecified   
Target Milestone: ---   
Host: Target:
Build: Last reconfirmed:

Description Mario Galindo 2020-02-06 01:10:42 UTC
Gcc has answered that this bug must be reported to you!

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();
}
Comment 1 Andreas Schwab 2020-02-19 11:06:24 UTC
I don't see anything calling the cleanup function in __pthread_once_slow.
Comment 2 Andreas Schwab 2020-02-19 11:15:23 UTC
dup

*** This bug has been marked as a duplicate of bug 18435 ***