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

时间:2019-06-01 14:12:39

标签: c++ multithreading

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

}

1 个答案:

答案 0 :(得分:1)

我怀疑由于以下两个错误,您的程序产生了超过200个线程。

首先,您的程序是未定义的行为,因为您同时从不同线程更改了 limit ,而没有任何同步机制,这是非法的。避免这种情况的最简单方法是使用atomic

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

第二,您应该在生成新线程之前 进行限制更新。否则,在您在其中的任何一个中运行limit += 2之前,新线程本身可能会生成新线程,依此类推。通常,不能保证不同线程在C ++中运行的顺序。