简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM