关于C++的线程thread,lambda,for循环动态生成线程

关于C++的线程thread,lambda,for循环动态生成线程,第1张

1、通过共享指针获取线程返回值

int main()
{
    vector<thread> vThread;
    vector<int*> nRst(5);
    for (size_t i = 0; i < 5; i++)
    {
        nRst[i] = new int(0);
    }
    for (int i = 0; i < 5; i++)
    {
        int a = 1;
        int b = 2;
        int *sumTemp = nRst[i];
        vThread.push_back(thread([a, b, i , sumTemp]()
            {
                *sumTemp = (a + b + i);
            }));
    }
    std::for_each(vThread.begin(), vThread.end(), [](thread& thr) {thr.join(); });
    for (size_t i = 0; i < 5; i++)
    {
        delete nRst[i];
    }
    return 0;
}

2、使用promise+future在thread和Lambda下返回值

#include
int main()
{
    int a = 1;
    int b = 2;
    std::promise<int> promiseObj;
    std::future<int> futureObj = promiseObj.get_future();
    std::thread thr = thread([a, b, &promiseObj]()
    {
        promiseObj.set_value(a + b);
    });
    thr.join();
    int sum = futureObj.get();
    cout << sum << endl;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/676117.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-19
下一篇 2022-04-19

发表评论

登录后才能评论

评论列表(0条)

保存