Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can std::future cause coredump without get or wait

void func() {
    std::future<int> fut = std::async(std::launch::async, []{
        std::this_thread::sleep_for(std::chrono::seconds(10));
        return 8; 
    });
    return;
}

Let’s say that I have such a function. An object fut of std::future<int> is initialized with a std::async job, which will return an integer in the future. But the fut will be immediately released after the function func returns.

Is there such an issue: When the std::async job returns and try to assign the 8 to the object fut, the object has already been released…

If so, a coredump about SIGSEGV may occur…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Am I right about it? Or std::future has some mechanism to avoid this issue?

>Solution :

Futures created with std::async have a blocking destructor that waits for the task to finish.

Even if you instead create a future from std::promise, the docs for ~future() don’t mention the problem you’re asking about.

The docs use the term "shared state" a lot, implying that a promise and a future share a (heap-allocated?) state, which holds the return value, and isn’t destroyed until both die.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading