Daniel Matei
Daniel Matei

Reputation: 43

How to check if the system has enough resources for another thread?

I'm writing a c++ function for merge sort using multithreading with the #include <thread> library and i don't know how to limit the number of threads such that the programs doesn't crash.

I tried putting the declaration of a the new thread in a try block but then i have run out of scope. The following is the code of the MergeSort function

vector < int > V;

// st == left margin of interval
// dr == right margin of interval 
void MergeSort( int st, int dr ) {

    static int limit = 0;

    int mid = ( st + dr ) / 2;

    if ( st >= dr ) {
        return ;
    }

    if ( limit > 200 ) {   // i tried to manually limit the number of threads 
        MergeSort( st, mid );
        MergeSort( mid + 1, dr );
        Merge( st, dr );                  // this merge the 2 sub arrays 
        return ;
    }

    thread t1 { MergeSort, st, mid };
    thread t2 { MergeSort, mid + 1, dr };

    limit += 2;

    t1.join();
    t2.join();

    limit -= 2;

    Merge( st, dr );

}

Upvotes: 2

Views: 63

Answers (1)

Brennan Vincent
Brennan Vincent

Reputation: 10675

I suspect that due to the following two bugs, your program is spawning far more than 200 threads.

First, your program is undefined behavior, since you are changing limit from different threads at the same time without any synchronization mechanism, which is illegal. The easiest way to avoid this is to use atomic:

static std::atomic<int> limit = 0;

Second, you should do the limit updating before you spawn the new threads. Otherwise, the new threads might themselves spawn new threads, and so on, and so on, before you ever run limit += 2 in any of them. In general the order in which different threads run in C++ is not guaranteed.

Upvotes: 1

Related Questions