codekiddy
codekiddy

Reputation: 6137

run thread from the class instance and also from the main

I'm trying to make following test program run:

#include <thread>
#include <iostream>
using namespace std;

struct foo
{
    void t1()
    {
        for(int i = 0; i < 5; ++i)
            cout << "thread 1" << endl;
    }

    thread bar()
    {
        return thread(&foo::t1, this);
    }
};


void t2()
{
    for(int i = 0; i < 5; ++i)
        cout << "main " << endl;
}


int main()
{
    foo inst;
    inst.bar();
    thread x(t2);

    return 0;
}

"thread 1" runs but application terminates when it's supposed to run thread "x" output is:

/home/user/dev/libs/llvm-3.4.2/bin/clang++ -std=c++11 -Wall -Wextra -pthread main.cpp -o 'Application' ./'Application' terminate called without an active exception thread 1 thread 1 thread 1 thread 1 thread 1 make: * [all] Aborted

the goal is to run 2 threads in the same time using an object instance within another function.

Upvotes: 0

Views: 99

Answers (2)

doctorlove
doctorlove

Reputation: 19272

You need to join (or detach) the thread:

int main()
{
    foo inst;
    inst.bar();
    thread x(t2);

    x.join(); //<-------

    return 0;
}

otherwise you see abort. Join will wait til the thread finishes.

Note that bar has returned you a thread which you haven't joined either which will give the same problem. Something like...

int main()
{
    foo inst;
    auto y = inst.bar();
    thread x(t2);
    x.join();
    if (y.joinable())
        y.join();
    return 0;
}

You may want to consider something like std::async instead.

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409356

It's because your process exits when the main function exits. You need to wait for the threads to finish (joining them), or detach them from the current process.

Upvotes: 1

Related Questions