我如何在 beaglebone black 上用 c++ 创建这么多线程
How can I create so many threads in c++ on beaglebone black
我想在 beaglebone black 上用 c++ 创建 500 多个线程 但是程序有错误。 您能否解释为什么会发生错误以及我如何修复错误
In thread func. : call_from_thread(int tid)
void call_from_thread(int tid)
{
cout << "thread running : " << tid << std::endl;
}
在主函数中。
int main() {
thread t[500];
for(int i=0; i<500; i++) {
t[i] = thread(call_from_thread, i);
usleep(100000);
}
std::cout << "main fun start" << endl;
return 0;
}
我期待
...
...
thread running : 495
thread running : 496
thread running : 497
thread running : 498
thread running : 499
main fun start
但
...
...
thread running : 374
thread running : 375
thread running : 376
thread running : 377
thread running : 378
terminate called after throwing an instance of 'std::system_error'
what(): Resource temporarily unavailable
Aborted
你能帮我吗?
beaglebone black似乎最大有512MB的DRAM。 根据 pthread_create() 线程的最小堆栈大小为 2MB。
即 2^29/2^21 = 2^8 = 256。因此,您可能会在线程 374 周围看到的是分配器无法足够快地释放内存以满足需求 通过引发异常来处理。
如果你真的想看到这种情况爆炸,试着在你的线程函数中移动这个睡眠调用。 :)
您可以尝试将堆栈预分配到 1MB 或更小(pthreads),但这有它 自己的一套问题。
真正要问自己的问题是:
-
我的应用程序是受 io 限制还是计算绑定?
-
运行此应用程序的内存预算是多少?如果您花费了整个物理内存 在线程堆栈上,共享程序堆将没有任何东西。
-
我真的需要这么多并行性来完成这项工作吗?顺便说一句,A8是单芯机器。
-
我可以使用线程池解决问题吗?或者根本不使用线程?
最后,您不能在 std::thread api 中设置堆栈大小,但您可以在 提升::线程。 或者只是在 pthreads 周围写一个薄包装器(假设 Linux)。
每当使用线程时,都会有三个部分。
- 启动线程
- 做工作
- 释放线程
您正在启动线程并执行工作,但您没有发布它们。
释放线程。有两个选项可用于释放线程。
- 你可以加入线程(基本上是等待它完成)
- 您可以分离线程,并让它独立执行。
在这种特殊情况下,您不希望程序在所有线程完成执行之前完成,因此您应该加入它们。
#include <iostream>
#include <thread>
#include <vector>
#include <string>
auto call_from_thread = [](int i) {
// I create the entire message before printing it, so that there's no interleaving of messages between threads
std::string message = "Calling from thread " + std::to_string(i) + 'n';
// Because I only call print once, everything gets printed together
std::cout << message;
};
using std::thread;
int main() {
thread t[500];
for(int i=0; i<500; i++) {
// Here, I don't have to start the thread with any delay
t[i] = thread(call_from_thread, i);
}
std::cout << "main fun startn";
// I join each thread (which waits for them to finish before closing the program)
for(auto& item : t) {
item.join();
}
return 0;
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息