user16204089
user16204089

Reputation:

Getting exception when calling std::call_once

I am trying a simple example to check the behavior of std::call_once(). I have tried the following code which doesn't do any useful work.

class Test {
  private:
    std::string obj_name;
    std::once_flag init_flag;

  public:
    Test(std::string name) : obj_name(name) {}

    void Init() {
        std::cout << "Initialization of " << obj_name << std::endl;
    }

    void Print() {
        try {
            std::call_once(init_flag, &Test::Init, this);
        } catch (const std::exception& ex) {
            std::cout << "Error: " << ex.what() << std::endl;
        }
        std::cout << "Inside Print() of "<< obj_name << std::endl;
    }
};

int main() {
    Test b1{"First object"};

    b1.Print();
    b1.Print();

    return 0;
}

I was expecting to see Print() called twice but getting an exception while calling std::call_once(). The output I got is -

Error: Unknown error -1
Inside Print() of First object
Error: Unknown error -1
Inside Print() of First object

To compile I've used -

g++ -g -std=c++11 -Wall -Werror

My question is why std::call_once() throwing exception? Or is it something I got wrong in my Print() method? If I change the body of Print() with just a return statement, it doesn't change anything.

Upvotes: 4

Views: 289

Answers (2)

nickelpro
nickelpro

Reputation: 2917

This is a GCC/libstdc++ bug, compile with -pthread to fix. See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55394

Upvotes: 5

Afshin
Afshin

Reputation: 9173

This is a really strange bug. I saw it both on GCC and Clang.

Compile your code with -pthread and everything works.

I don't know why come compiles and runs, but it does not works correctly. I was expecting that code does not link. If you add pthread, it works as expected.

Upvotes: 0

Related Questions