【发布时间】: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() 是否正常工作。
【问题讨论】:
-
无关,我会先好好利用神秘包含但从未使用过的
<vector>,而不是自己管理动态分配。 -
“安全”是什么意思? “正常工作”与“正常工作”有何不同?
-
我不明白你所说的“嵌套线程”是什么意思——什么是嵌套?
-
这并不能解决问题,但不要使用
std::endl,除非您需要它所做的额外内容。'\n'结束一行。
标签: c++ multithreading c++11 stdthread