Sid
Sid

Reputation: 1269

C++ Creating a thread with non static member function

I'm trying to create a new thread in c++ with a non static member function of a class. However this seems to be crashing consistently on a mac and I can't figure out why. Here's a minimal example:

class A {
public:
    void hello() {
        cout << "hello" << endl;
    }

    A() {
        cout << "As constructor" << endl;
        // thread(&hello, this);
    }

    void start() {
        thread(&A::hello, this);
    }
};

int main(){
    A test;
    test.start();

}

I'm compiling on a mac with this:

clang++ -std=c++11 -stdlib=libc++ -pthread -o hello thread.cpp 

What am I missing?

Upvotes: 0

Views: 908

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596527

The problem is two-fold:

  • main() does not wait for the thread to complete before destroying the test object, which CAN cause a crash.

  • start() is not storing the std::thread object anywhere, so it gets destroyed immediately, which WILL cause a crash because the thread is still joinable and the std::thread destructor calls std::terminate() to kill the calling process if the thread is joinable.

Try something more like this instead:

class A {
private:
    std::thread thrd;

public:
    void hello() {
        cout << "hello" << endl;
    }

    A() {
        cout << "As constructor" << endl;
    }

    ~A() {
        cout << "As destructor" << endl;
        wait();
    }

    void start() {
        thrd = thread(&A::hello, this);
    }

    void wait() {
        if (thrd.joinable())
            thrd.join();
    }
};

int main(){
    A test;
    test.start();
    // do something else while the thread is running...
}

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172934

You should call std::thread::join to block the current thread until the thread created finishing execution. Otherwise the current thread might finish and cause the object test to be destroyed in advance.

e.g.

void start() {
    thread t(&A::hello, this);
    t.join();
}

Upvotes: 3

Related Questions