mardi 23 février 2016

Confusion in understanding thread::join() in "The C++ Programming Language"

When reading "The C++ Programming Language, 4th Edition" by Bjarne Stroustrup, section 42.2.4 join() of the new thread class in STL. It has an example code, that confuses me.

void run(int i, int n) // warning: really poor code
{
    thread t1 {f};
    thread t2;
    vector<Foo> v;
    // ...
    if (i<n) {
        thread t3 {g};
        // ...
        t2 = move(t3); // move t3 to outer scope
    }
    v[i] = Foo{}; // might throw
    // ...
    t1.join();
    t2.join();
}

It has these comments after the code snippet:

Here, I have made several bad mistakes. In particular:

  • We may never reach the two join()s at the end. In that case, the destructor for t1 will terminate the program.

  • We may reach the two join()s at the end without the move t2=move(t3) having executed. In that case, t2.join() will terminate the program.

Why we may never reach the two joins(), why the destructor for t1 is called before t1.join()?

Aucun commentaire:

Enregistrer un commentaire