我如何在 beaglebone black 上用 c++ 创建这么多线程

How can I create so many threads in c++ on beaglebone black

本文关键字:创建 c++ 多线程 上用 black beaglebone      更新时间:2023-10-16

我想在 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;
}