【问题标题】:Does std::thread library in C++ support nested threading?C++ 中的 std::thread 库是否支持嵌套线程?
【发布时间】:2017-03-15 10:19:44
【问题描述】:

我想使用像这样的std::thread 库在 C++ 中创建嵌套线程。

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

void innerfunc(int inp)
{
    cout << inp << endl;
}
void outerfunc(int inp)
{
    thread * threads = new thread[inp];
    for (int i = 0; i < inp; i++)
        threads[i] = thread(innerfunc, i);
    for (int i = 0; i < inp; i++)
        threads[i].join();
    delete[] threads;
}
int main()
{
     int inp = 0;
     thread t1 = thread(outerfunc,2);
     thread t2 = thread(outerfunc,3);
     t1.join();
     t2.join();
}

我可以安全地执行此操作吗?我担心join() 是否正常工作。

【问题讨论】:

  • 无关,我会先好好利用神秘包含但从未使用过的&lt;vector&gt;,而不是自己管理动态分配。
  • “安全”是什么意思? “正常工作”与“正常工作”有何不同?
  • 我不明白你所说的“嵌套线程”是什么意思——什么是嵌套?
  • 这并不能解决问题,但不要使用std::endl,除非您需要它所做的额外内容。 '\n' 结束一行。

标签: c++ multithreading c++11 stdthread


【解决方案1】:

C++ 中并没有真正意义上的“嵌套”或“子”线程,操作系统模型不会立即映射到 C++。 C++ 的模型更准确地描述为threads of execution being associated with thread objects

来自链接的 cppreference;

类线程代表单个执行线程。

thread 对象可以根据需要移动(std::move);这实际上更多是所有权问题,谁需要在对象超出范围之前join() thread

回答问题;

我可以安全地做到这一点吗?

是的。执行线程(及其关联的thread 对象)可以在“嵌套”线程中创建并成功执行。

我担心join() 是否正常工作。

是的,它会的。这与线程的“所有权”有关。只要在thread 对象超出范围之前加入执行线程,它就会按预期工作。


附带说明;我确定innerfunc 仅用于演示,但cout 可能不会按预期同步。输出会“乱码”。

【讨论】:

  • 我不认为“子线程”是一回​​事。就 C++ 线程模型而言,线程之间没有关系。所有线程都是平等的,任何一个线程都可以加入任何其他线程。
  • 正确,但 OP 的措辞是“嵌套”线程,暗示他的内部逻辑正在订购这些。我将对此添加一些注释。
  • 当然,这里的全部问题是 OP 正遭受毫无根据的误解。我想我的意思是,如果有意义的话,答案可能应该从 那里 开始,而不是通过遵循 OP 的规则并探索不存在的概念。
  • 正确。我将从这个答案开始。
【解决方案2】:

一切正常!只需为所有“cout”语句添加一个锁。否则数值会乱码。

mutex m;

void innerfunc(int inp)
{
    m.lock();
    cout <<"Innerfunc triggered " << inp << endl;
    m.unlock();
}

void outerfunc(int inp)
{
    m.lock();
    cout <<"Outerfunc triggered " << inp << endl;
    m.unlock();
    thread * threads = new thread[inp];
    for (int i = 0; i < inp; i++)
        threads[i] = thread(innerfunc, i);
    for (int i = 0; i < inp; i++)
        threads[i].join();
    delete[] threads;
}

【讨论】:

    猜你喜欢
    • 2011-11-06
    • 2016-09-18
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 2019-11-07
    相关资源
    最近更新 更多