Home > Backend Development > C++ > Why Does the `std::future` Destructor Returned by `std::async` Block?

Why Does the `std::future` Destructor Returned by `std::async` Block?

Mary-Kate Olsen
Release: 2024-11-15 14:26:02
Original
932 people have browsed it

Why Does the `std::future` Destructor Returned by `std::async` Block?

Blocking Nature of std::future Destructor Returned by std::async

While intending to launch a task asynchronously, it was discovered that the destructor of a std::future returned by std::async exhibits blocking behavior. This raised questions about the rationale behind this design decision and whether it could be improved for convenience and efficiency.

Arguments for Blocking Destructor

One of the primary concerns addressed by the blocking destructor is preventing "runaway" threads. If the std::future was destroyed without waiting for the associated thread to complete, it could lead to unpredictable behavior and potential memory corruption.

As described in Hans Boehm's paper (N3679), this issue can arise when a thread operates on data that has already been destroyed. Without a blocking destructor, the thread could potentially continue to access and modify that data, leading to cross-thread memory issues.

Alternative Approaches

Some have suggested that a non-blocking destructor would be sufficient if the get or wait methods were always called to retrieve the result or wait for completion. However, Boehm argues that relying on explicit calls prone to oversight and could lead to security vulnerabilities. Exceptional circumstances, such as exceptions during execution, could bypass such calls and result in the creation of runaway threads.

Current Status and Future Developments

Despite ongoing discussions within the C standards committee, there are no changes planned for the blocking behavior of std::future destructors in C 14. However, the issue remains under consideration, and future versions of C may address this behavior.

Recommendations for Practice

To avoid the potential problems associated with blocking destructors, it is recommended to always call get or wait before destroying a std::future returned by std::async. This ensures that the associated thread has completed its execution and all necessary resources have been released.

The above is the detailed content of Why Does the `std::future` Destructor Returned by `std::async` Block?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template