vendredi 25 août 2017

How to limit the standart library thread count?

I want to limit the number of thread for a given job. Here is a sample code of my attempts to do so:

 #DEFINE MAX_THREAD_COUNT 5;

Later:

void MyClass::a_method() {
    unsigned thread_count;
    std::vector<std::thread> jobs;

    std::vector<AnObject> collection;

    for(auto& c : collection) {
        if(thread_count >= MAX_THREAD_COUNT) {
            for(auto& j : jobs) {
                if(j.joinable()) {
                    j.join();
                    thread_count--;
                }
            }  
        }

        t.push_back(std::thread([=] { this->a_long_job(c); }));
    }

    for(auto& j : jobs) {
        if(j.joinable()) {
            j.join();
        }
    } 
}

The problem is that sometimes this->a_long_job isn't call all the time, I checked this by printing a line inside the method and by printing the number of elements contained in collection.

Another idea that could work but isn't elegant would be to launch max_thread threads with c/max_thread calls of this->a_long_job(c) in each.

I don't think that I need a thread pool for this application because there's a need only in this method.

Notes:

  • No external libraries
  • C++11 and further

Aucun commentaire:

Enregistrer un commentaire