简体   繁体   中英

recursive threading with C++ gives a Resource temporarily unavailable

So I'm trying to create a program that implements a function that generates a random number (n) and based on n, creates n threads. The main thread is responsible to print the minimum and maximum of the leafs. The depth of hierarchy with the Main thread is 3.

I have written the code below:

#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;

}

The code compiles with no error, but when I execute it, it gives me this :

libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: thread constructor failed: Resource temporarily unavailable Abort trap: 6

You spawn too many threads. It looks a bit like a fork() bomb. Threads are a very heavy-weight system resource. Use them sparingly.

Within the function void Childwork I see two mistakes:

  1. As someone already pointed out in the comments, you check the info level of a thread and then you go and create some more threads regardless of the previous check.

  2. Within the for loop that spawns your new threads, you increment the info level right before you spawn the actual thread. However you increment a freshly created instance of ThreadInfo here ThreadInfo* childInfo = new ThreadInfo[(int)n] . All instances within childInfo hold a level of 0. Basically the level of each thread you spawn is 1.

In general avoid using threads to achieve concurrency for I/O bound operations (*). Just use threads to achieve concurrency for independent CPU bound operations. As a rule of thumb you never need more threads than you have CPU cores in your system (**). Having more does not improve concurrency and does not improve performance.

(*) You should always use direct function calls and an event based system to run pseudo concurrent I/O operations. You do not need any threading to do so. For example a TCP server does not need any threads to serve thousands of clients.

(**) This is the ideal case. In practice your software is composed of multiple parts, developed by independent developers and maintained in different modes, so it is ok to have some threads which could be theoretically avoided.

Multithreading is still rocket science in 2019. Especially in C++. Do not do it unless you know exactly what you are doing. Here is a good series of blog posts that handle threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM