【问题标题】:run thread from the class instance and also from the main从类实例和主线程运行线程
【发布时间】:2014-07-29 10:46:29
【问题描述】:

我正在尝试运行以下测试程序:

#include <thread>
#include <iostream>
using namespace std;

struct foo
{
    void t1()
    {
        for(int i = 0; i < 5; ++i)
            cout << "thread 1" << endl;
    }

    thread bar()
    {
        return thread(&foo::t1, this);
    }
};


void t2()
{
    for(int i = 0; i < 5; ++i)
        cout << "main " << endl;
}


int main()
{
    foo inst;
    inst.bar();
    thread x(t2);

    return 0;
}

“线程 1”运行但应用程序在它应该运行线程“x”时终止 输出是:

/home/user/dev/libs/llvm-3.4.2/bin/clang++ -std=c++11 -Wall -Wextra -pthread main.cpp -o 'Application' ./'Application' 在没有活动异常的情况下终止调用线程 1 线程 1 线程 1 线程 1 线程 1 个品牌:* [all] 中止

目标是使用另一个函数中的对象实例同时运行 2 个线程。

【问题讨论】:

    标签: c++ multithreading c++11


    【解决方案1】:

    你需要加入(或分离)线程:

    int main()
    {
        foo inst;
        inst.bar();
        thread x(t2);
    
        x.join(); //<-------
    
        return 0;
    }
    

    否则你会看到中止。 Join 会一直等到线程结束。

    请注意,bar 已向您返回一个您尚未加入的线程,这将产生同样的问题。有点像...

    int main()
    {
        foo inst;
        auto y = inst.bar();
        thread x(t2);
        x.join();
        if (y.joinable())
            y.join();
        return 0;
    }
    

    您可能需要考虑使用 std::async 之类的东西。

    【讨论】:

    • 我复制了你的“main”并替换为我的,但仍然是同样的错误:(
    • std::async FTW。来自 Scott Meyers here 的一些有趣的注释
    【解决方案2】:

    这是因为你的进程main函数退出时退出。您需要等待线程完成 (joining them),或等待当前进程中的 detach them

    【讨论】:

    • 谢谢,我在return之前加入了线程“x”,仍然导致错误,请你澄清你的答案吗?
    • 退出main 或调用exit 会破坏所有线程,无论它们是否分离。但是可以终止主线程,这样它就永远不会离开main 并调用exit
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    相关资源
    最近更新 更多