Thread Pool C++

Viewed 9119

I have the following for loop:

for (int i = 0; i < 100; i++) {
    someJob();
}

I want to run this function only with 5 threads, how can I do it?
I can't use any external library.

What I've tried is to make an array with 5 threads and if the index is equal to 5 to wait all threads and do it again, but I'm sure there is another way to do that:

std::thread t[THREAD_COUNT];
int j=0;

for (int i = 0; i < 100; i++) {
    t[j++] = std::thread(someJob);
    if (j == THREAD_COUNT)
    {
        for (int k = 0; k < THREAD_COUNT; k++)
        {
            if (t[k].joinable())
                t[k].join();
        }
        j = 0;
    }
}

Any suggestion? (I can't use boost)

Thanks!

5 Answers
Related