【发布时间】:2017-05-04 08:24:13
【问题描述】:
所以,我编写了一个生成曼德布罗图像的程序。然后,我决定以一种使用指定数量的线程来加速它的方式编写它。这是我想出的:
void mandelbrot_all(std::vector<std::vector<int>>& pixels, int X, int Y, int threadCount) {
using namespace std;
vector<thread> threads;
int numThreads = threadCount;
for(int i=0; i<numThreads; i++) {
threads.push_back(thread (mandelbrot_range, std::ref(pixels), i*X/numThreads, 0, X*(i+1)/numThreads, Y, X));
}
for(int i=0; i<numThreads; i++) {
threads[i].join();
}
}
其目的是将处理分成块并分别处理每个块。当我运行程序时,它需要一个数字作为参数,它将用作程序中用于该运行的线程数。不幸的是,对于任何数量的线程,我都会得到相似的时间。
C++ 中的线程有什么我缺少的吗?我是否必须添加一些东西或某种样板才能使线程同时运行?还是我制作线程的方式很傻?
我尝试在树莓派和我的四核笔记本电脑上运行此代码,结果相同。
任何帮助将不胜感激。
【问题讨论】:
-
启动线程有点贵。所以你想做一个需要几秒钟以上的测试。此外,如果您有一个用于保护数据的互斥锁,它可能会序列化您的线程。
-
您能解释一下“用于保护数据的互斥锁”是什么意思吗?
-
其实不是。他在问一些完全不同的事情。
-
您很可能正在破坏数据线或指令缓存中的一个(或两个)。您可能想阅读:herbsutter.com/welcome-to-the-jungle
标签: c++ multithreading mandelbrot