C 中的std ::线程库支持嵌套线程

Does std::thread library in C++ support nested threading?

本文关键字:线程 支持 嵌套 中的 std      更新时间:2023-10-16

我想使用这样的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()是否正常工作。

实际上没有诸如C 中的"嵌套"或"儿童"线程,OS模型不会立即映射到C 。C 的模型沿与thread对象关联的执行线的线条更准确地描述了。

来自链接的cppreference;

类线程表示执行的单个线程。

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

回答问题;

我可以安全地做吗?

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

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

是的。这与线程的"所有权"有关。只要在 thread对象不在范围之前加入执行线,它将按照您的期望工作。


在旁注;我确定innerfunc仅用于演示,但是cout可能不会像预期的那样同步。输出将"乱七八糟"。

一切正常!只需为所有" 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;
}