gpt4 book ai didi

c++ - 如何在 for 循环中运行并行线程 (C++)

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:21:08 28 4
gpt4 key购买 nike

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

我基本上想并行运行 16 个线程,每个线程渲染一个 mandelbrot 图像。我看不出如何在 for 循环中实现这一点,因为我必须等待线程完成才能创建新线程。

有没有一种方法可以让我运行并行线程,而不必一个接一个地创建 16 个线程?

最佳答案

很明显,您需要在跟踪的同时异步运行它们:

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

关于c++ - 如何在 for 循环中运行并行线程 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48706973/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com