vendredi 27 décembre 2019

What is the lifetime of C++ member variables when running in a std::thread?

#include <iostream>
#include <string>
#include <thread>

using namespace std;

struct safe_thread : public thread
{
    using thread::thread;

    safe_thread& operator=(safe_thread&&) = default;

    ~safe_thread()
    {
        if (joinable())
        {
            join();
        }
    }
};

struct s
{
    safe_thread t;
    std::string text = "for whatever reason, this text will get corrupted";

    s() noexcept
    {
        std::cout << text << '\n'; // it works in constructor as expected
        t = safe_thread{ [this]
                         { long_task(); }};
    }

    s(s&&) noexcept = default;

    void long_task()
    {
        for (int i = 0; i < 500; ++i)
        {
            std::cout << text << '\n'; // the text gets corrupted in here
        }
    }
};

int main()
{
    s s;
}

In the code above, the text variable would print correctly in the constructor. However, in the long_task() function running in a separate thread, the text gets corrupted (it outright crashes on another machine). How is that so? If the destructor of safe_thread would be run in the destructor of struct s, shouldn't the lifetime of thread and text last equally long? I.e they would both go out of scope when s goes out of scope at main()?

Aucun commentaire:

Enregistrer un commentaire