0

Here is an example code:

struct T
{
    T()
    {
        task = std::async(std::launch::async, [this]()
        {
            while(work)
            {
                //do something
            }
        });
    }

    ~T()
    {
        work = false;
    }

    std::future<void> task;
    std::atomic_bool work;
};

Should I somehow finalize future in the destructor or the above code is ok ?

Irbis
  • 11,537
  • 6
  • 39
  • 68

1 Answers1

0

The code you show is not okay, but not for the reason you may think. Since the shared state referred to by task was created by std::async, the d'tor of std::future will block when destroying task. But that still won't help you.

The problem is that members of a class are destroyed in reverse order to their initialization. Since work is initialized last, it will be destroyed before task. So even though you set it to false, your task may in fact be referring to a dead object when it runs the check in the loop. So you'll have undefined behavior on your hands.

You can solve it by moving work before task, so its lifetime is longer. Or you may explicitly call task.wait() in the destructor of T. Personally, I think the latter is clearer.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458