C++中的std :: thread库是否支持嵌套线程?

sat*_*tya 1 c++ multithreading c++11 stdthread

我想使用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();
}
Run Code Online (Sandbox Code Playgroud)

我可以安全地这样做吗?我担心是否join()正常工作.

Nia*_*all 5

在C++中没有"嵌套"或"子"线程这样的东西,操作系统模型不会立即映射到C++.C++模型可以根据thread对象关联的执行线程更准确地描述.

来自链接的cppreference;

类线程表示单个执行线程.

thread对象可以根据需要移动(std::move); 它确实是更所有权的问题,谁需要join()thread是超出范围之前的对象.

在回答问题时;

我可以安全地这样做吗?

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

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

是的,它会的.这与线程的"所有权"有关.只要在thread对象超出范围之前连接执行线程,它就会按预期工作.


旁注; 我确定它innerfunc仅用于演示,但cout可能不会按预期同步.输出将是"乱码".