Kingpin
Kingpin

Reputation: 95

How to run parallel threads in a for loop (C++)

for (int i = 0; i < 16; i++)
{
    thread myThread(compute_mandelbrot, -2.0, 1.0, 1.125, -1.125, ystart, yend);
    ystart = ystart + 30;
    yend = yend + 30;
    myThread.join();
}

I essentially want to run 16 threads parallel, with each thread rendering a piece of a mandelbrot image. I don't see how i can achieve this is in a for loop as i have to wait for the thread to complete before a new thread is created.

Is there a way for me to run parallel threads without having to creating 16 threads one after another?

Upvotes: 1

Views: 1307

Answers (3)

Kingpin
Kingpin

Reputation: 95

I created an array of threads using the simplest notation i could use creating all 16 threads and then joining all 16 in another for loop.

for (int i = 0; i < 16; i++, ystart += 30, yend += 30)
{
    threadArr[i] = thread(compute_mandelbrot, -2.0, 1.0, 1.125, -1.125, ystart, yend);
}
for (int i = 0; i < 16; i++)
{
    threadArr[i].join();
}

Upvotes: 0

Holt
Holt

Reputation: 37686

You need to create all std::thread before calling join(), otherwise you are waiting for a thread to terminate before starting the next one.

An easy way to do that is to store the threads in an array:

constexpr size_t nthreads = 16;

std::array<std::thread, nthreads> threads;

// fill the array with threads
for (auto &thread: threads) {
    thread = std::thread(compute_mandelbrot, -2.0, 1.0, 
                         1.125, -1.125, ystart, yend);
    ystart = ystart + 30;
    yend = yend + 30;
}

// join everything
for (auto &thread: threads) {
    thread.join();
}

Upvotes: 4

bipll
bipll

Reputation: 11950

Well, obviously you'll need to run them asynchronously while keeping track:

// DISCLAIMER: not a real production code
std::vector<std::thread> workers;
// first start them all
for(std::size_t i{}; i < 16; ++i, ystart += 30, yend += 30) {
    workers.emplace_back(compute_mandelbrot, -2.0, 1.0, 1.125, -1.125, ystart, yend);
}
// now join them all
for(auto &w: workers) w.join();

Upvotes: 6

Related Questions