vendredi 18 octobre 2019

How to terminate a thread safely? (with the usage of pointer) c++

I am currently learning multithreading in c++11 and I am confused with the way to terminate a thread safely.

In c++, I know the way to create threads and use thread.join() to safely ensure main() to wait for all threads to finish before quitting itself.

However, I found that some multithread codes implemented via pointers are able to run even without using thread.join().

class Greating
{
public:

    Greating(const int& _i):i_(_i){}
    ~Greating(){}
    int i_;
    void say()
    {
        std::cout << "Hello World" << i_ << std::endl;
    }

};

int main(){
    Greating greating1(1);
    Greating greating2(2);

    std::thread t1(&Greating::say, greating1);
    std::thread t2(&Greating::say, greating2);
    return 0;
}

The code shown above will absolutely report the error "terminate called without an active exception Aborted (core dumped)", because I did not use t1.join() and t2.join().

However, I found in some codes when they use the pointer to manage the thread, this does not become a problem, as shown below.

class Greating
{
public:

    Greating(const int& _i):i_(_i){}
    ~Greating(){}
    int i_;
    void say()
    {
        std::cout << "Hello World" << i_ << std::endl;
    }

};

int main(){
    Greating greating1(1);
    Greating greating2(2);

    std::thread* tt1 = new std::thread(&Greating::say, greating1);
    std::thread* tt2 = new std::thread(&Greating::say, greating2);
    return 0;
}

The output is:

Hello WorldHello World12
Hello World12

There is no error reported. This made me very confused.

So my question is:

  1. Why when we use pointer to manage the thread, we could not use the function thread.join()?
  2. How to correctly terminate a thread? (probably wait for the callable function to finish?)

Thanks very much!

Aucun commentaire:

Enregistrer un commentaire