因此,我试图创建一个程序,该程序实现一个函数,该函数生成一个随机数(n),并基于n创建n个线程。主线程负责打印最小和最大的叶子。主线程的层次结构深度为3。
我已经编写了以下代码:
#include <iostream>
#include <thread>
#include <time.h>
#include <string>
#include <sstream>
using namespace std;
// a structure to keep the needed information of each thread
struct ThreadInfo
{
long randomN;
int level;
bool run;
int maxOfVals;
double minOfVals;
};
// The start address (function) of the threads
void ChildWork(void* a) {
ThreadInfo* info = (ThreadInfo*)a;
// Generate random value n
srand(time(NULL));
double n=rand()%6+1;
// initialize the thread info with n value
info->randomN=n;
info->maxOfVals=n;
info->minOfVals=n;
// the depth of recursion should not be more than 3
if(info->level > 3)
{
info->run = false;
}
// Create n threads and run them
ThreadInfo* childInfo = new ThreadInfo[(int)n];
for(int i = 0; i < n; i++)
{
childInfo[i].level = info->level + 1;
childInfo[i].run = true;
std::thread tt(ChildWork, &childInfo[i]) ;
tt.detach();
}
// checks if any child threads are working
bool anyRun = true;
while(anyRun)
{
anyRun = false;
for(int i = 0; i < n; i++)
{
anyRun = anyRun || childInfo[i].run;
}
}
// once all child threads are done, we find their max and min value
double maximum=1, minimum=6;
for( int i=0;i<n;i++)
{
// cout<<childInfo[i].maxOfVals<<endl;
if(childInfo[i].maxOfVals>=maximum)
maximum=childInfo[i].maxOfVals;
if(childInfo[i].minOfVals< minimum)
minimum=childInfo[i].minOfVals;
}
info->maxOfVals=maximum;
info->minOfVals=minimum;
// we set the info->run value to false, so that the parrent thread of this thread will know that it is done
info->run = false;
}
int main()
{
ThreadInfo info;
srand(time(NULL));
double n=rand()%6+1;
cout<<"n is: "<<n<<endl;
// initializing thread info
info.randomN=n;
info.maxOfVals=n;
info.minOfVals=n;
info.level = 1;
info.run = true;
std::thread t(ChildWork, &info) ;
t.join();
while(info.run);
info.maxOfVals= max<unsigned long>(info.randomN,info.maxOfVals);
info.minOfVals= min<unsigned long>(info.randomN,info.minOfVals);
cout << "Max is: " << info.maxOfVals <<" and Min is: "<<info.minOfVals;
}
代码编译没有错误,但是当我执行它时,它给了我:
libc ++ abi.dylib:以类型未捕获的异常终止 std :: __ 1 :: system_error:线程构造函数失败:资源 暂时不可用的中止陷阱:6
答案 0 :(得分:3)
您生成了太多线程。它看起来有点像fork()
炸弹。线程是非常重的系统资源。少用。
在函数void Childwork
中,我看到两个错误:
正如评论中已经指出的那样,您检查线程的信息级别,然后不管先前的检查如何,都可以创建更多线程。
在产生新线程的for循环中,您在生成实际线程之前立即增加信息级别。但是,您在ThreadInfo
处递增了ThreadInfo* childInfo = new ThreadInfo[(int)n]
的新创建实例。 childInfo中的所有实例的级别均为0。基本上,您产生的每个线程的级别为1。
通常,避免使用线程来实现I / O绑定操作(*)的并发。只需使用线程即可为独立的CPU绑定操作实现并发性。根据经验,您所需要的线程数永远不会超过系统中具有CPU内核(**)的线程数。拥有更多内容不会提高并发性,也不会提高性能。
(*)您应该始终使用直接函数调用和基于事件的系统来运行伪并发I / O操作。您不需要任何线程来执行此操作。例如,TCP服务器不需要任何线程即可为数千个客户端提供服务。
(**)这是理想的情况。实际上,您的软件由独立开发人员开发并由不同模式维护的多个部分组成,因此可以从理论上避免一些线程。
2019年,多线程仍然是火箭科学。尤其是在C ++中。除非您确切知道自己在做什么,否则不要这样做。这是一个处理线程的good series of blog posts。