C 中的std ::线程库支持嵌套线程
Does std::thread library in C++ support nested threading?
我想使用这样的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;
}
相关文章:
- 具有多线程支持的 RenderClass,将函数调用推送到向量以在另一个线程上调用
- C 中的std ::线程库支持嵌套线程
- Eclipse c++11 线程支持不起作用
- 适用于 C++11 的 Clang++ 3.3 中的线程支持
- 为不受支持的平台调整Boost线程/进程
- 在使用Win32线程模型时,MinGW-w64是否支持开箱即用的std::线程
- 带有C 11和线程支持的Visual Express C
- 支持多线程方法来构建数组中所有元素的集合吗
- 需要一个支持 16 位整数 (c++) 的免费线程安全矩阵数学库
- 使用串行端口线程进行 CPU 支持
- 在Windows上使用WaitForSingleObject,但支持boost线程中断
- 对std::线程的drd和helgrind支持的当前状态
- 为什么新式C++库不支持优先级线程?
- 支持多线程的c++ HashMap
- 链接时间优化与多线程支持冲突
- 收到此错误时如何实现非托管线程安全集合: <mutex> 使用 /clr 编译时不支持
- 如何使线程安全 支持"<<"操作的日志类?
- C++是否提供内置的多线程支持
- 如何使用cmake和Android NDK在C++中加载线程支持
- 如何在Mac OS X上使用clang获得新的c++线程支持?