C++ Multithreading - correct way to limit the number of concurrent std::async threads

39 views Asked by At

I have a program that parallelizes some I/O file reading via std::async on a workstation. Since other users also use the workstation in question, I want to limit the number of concurrent threads.

Here is a minimal (kind of) working example of the solution that I came up with.

#include <future>
#include <vector>

void do_concurrent_stuff(int thread_id)
{
    // read a file and do some calculations here
}

int main()
{
    const int n_max_threads = 10;
    std::vector<std::future<void>> results;

    for (int i; i < 1000; i++)
    {
        while(results.size() > n_max_threads)
        {
            for (int thread = 0; thread < results.size(); thread++)
            {
                const auto response = results[thread].wait_for(std::chrono::seconds(0));
                if (response == std::future_status::ready)
                {
                    results.erase(results.begin() + thread);
                }
            }
        }
        results.push_back(std::launch::async, do_concurrent_stuff, i);
    }

    return 0;
}

I have the feeling what I am doing isn't ideal. How does one properly limit the number of threads a program spawns?

0

There are 0 answers