【问题标题】:detach call is not working as per expectation分离呼叫未按预期工作
【发布时间】:2019-05-02 18:31:23
【问题描述】:

需要帮助为什么以下代码的工作方式不同。 在此代码中,主退出后线程不打印任何内容:

#include <iostream>
#include <chrono>
#include <thread>

using namespace std;

void Run()
{

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;

}

int main()
{
    std::thread th(Run);

    th.detach();

    std::this_thread::sleep_for(std::chrono::seconds(2));

    cout<<"==== Ending main ==="<<std::endl;
}

但是这里在线程退出后会打印正确的消息:

void independentThread() 
{
    std::cout << "Starting concurrent thread.\n";
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Exiting concurrent thread.\n";
}

void threadCaller() 
{
    std::cout << "Starting thread caller.\n";
    std::thread t(independentThread);
    t.detach();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Exiting thread caller.\n";
}

int main() 
{
    threadCaller();
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

应该是非常小的东西,我想念它。 编译器信息: g++/Mac/c++11

试图在谷歌上搜索,但没有运气。

编辑-1: 第一个程序的结果:

=== start_point ===
=== start_point ===
==== Ending main ===

第二个项目的结果:

Starting thread caller.
Starting concurrent thread.
Exiting thread caller.
Exiting concurrent thread.

【问题讨论】:

    标签: multithreading c++11 detach


    【解决方案1】:

    在我看来,该代码执行正确。

    通常当thread的析构函数运行时,它会等待线程完成后再退出。但是,当您调用 detach() 时,您正在规避这种行为 - 当前方法不会等待线程完成。

    由于线程将运行(大约)6 秒,main() 中的睡眠不会等待足够长的时间来完成威胁,因此它将在线程完成之前退出。根据环境,退出main() 也可能会退出程序——这意味着线程在程序退出之前没有机会打印其所有消息。

    如果您想显式等待线程完成后再继续执行,您应该调用thread::join()

    【讨论】:

    • 感谢您的回复。那为什么即使在 main 退出后仍然为第二个程序工作。
    • 我知道我们可以使用 Join,但我只想知道为什么他们的行为不同。我错过了基本的东西吗?!!!
    • 知道了。感谢您的答复。它是在 main 退出后阻塞执行的系统环境。如果我增加线程的睡眠时间,第二个程序也会发生同样的情况。再次感谢安迪。
    猜你喜欢
    • 1970-01-01
    • 2020-03-12
    • 2018-10-06
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    相关资源
    最近更新 更多