为什么这个 future.wait_until 示例有 thread.detach() ?detach 不会导致内存泄漏吗?

flo*_*cca 1 c++ multithreading

https://en.cppreference.com/w/cpp/thread/future/wait_until有一个在线程上调用 detach 的示例。为什么使用detach()?不会导致线程内存泄漏吗?cppreference 使用不好的技术似乎很奇怪。这是代码:

#include <iostream>
#include <future>
#include <thread>
#include <chrono>
 
int main()
{
    std::chrono::system_clock::time_point two_seconds_passed
        = std::chrono::system_clock::now() + std::chrono::seconds(2);
 
    // Make a future that takes 1 second to complete
    std::promise<int> p1;
    std::future<int> f_completes = p1.get_future();
    std::thread([](std::promise<int> p1)
                { 
                    std::this_thread::sleep_for(std::chrono::seconds(1)); 
                    p1.set_value_at_thread_exit(9); 
                }, 
                std::move(p1)
    ).detach();
 
    // Make a future that takes 5 seconds to complete
    std::promise<int> p2;
    std::future<int> f_times_out = p2.get_future();
    std::thread([](std::promise<int> p2)
                { 
                    std::this_thread::sleep_for(std::chrono::seconds(5)); 
                    p2.set_value_at_thread_exit(8); 
                }, 
                std::move(p2)
    ).detach();
 
    std::cout << "Waiting for 2 seconds..." << std::endl;
 
    if(std::future_status::ready == f_completes.wait_until(two_seconds_passed))
        { std::cout << "f_completes: " << f_completes.get() << "\n"; }
    else
        { std::cout << "f_completes did not complete!\n"; }
 
    if(std::future_status::ready == f_times_out.wait_until(two_seconds_passed))
        { std::cout << "f_times_out: " << f_times_out.get() << "\n"; }
    else
        { std::cout << "f_times_out did not complete!\n"; }
 
    std::cout << "Done!\n";
}
Run Code Online (Sandbox Code Playgroud)

Ala*_*les 5

detach不会导致内存泄漏,线程结束时仍然会被销毁。

它所做的是将线程的生命周期与其声明的范围分离,如果线程使用的变量位于同一范围内,这会导致问题。这些变量将在线程完成之前被销毁,从而导致未定义的行为。

正确使用并没有什么问题,detach但是通常不使用它比使用它更容易编写正确的程序detach

在此示例中,线程不访问任何外部变量,因此detach可以安全使用。我想这里使用它是为了避免使用join线程,这会分散他们所演示的承诺的使用。