我正在添加代码作为参考,但您可能不需要了解mandlerbot来帮助我解决这种奇怪的多线程副作用。
我正在使用此代码生成一个简单的Mandelbrot:
void compute_mandelbrot(double left, double right, double top, double bottom, double start, double end)
{
int r = 0x00, g = 0x00, b = 0x00;
for (int y = start; y < end; ++y)
{
for (int x = 0; x < WIDTH; ++x)
{
// Work out the point in the complex plane that
// corresponds to this pixel in the output image.
complex<double> c(left + (x * (right - left) / WIDTH),
top + (y * (bottom - top) / HIGHT));
// Start off z at (0, 0).
complex<double> z(0.0, 0.0);
// Iterate z = z^2 + c until z moves more than 2 units
// away from (0, 0), or we've iterated too many times.
int iterations = 0;
while (abs(z) < 2.0 && iterations < MAX_ITERATIONS)
{
z = (z * z) + c;
++iterations;
}
if (r <= MAX_ITERATIONS)
r = iterations;
unsigned int colour = r | (r << 8) | (r << 16);
vertex.color = sf::Color(r, g, b, 255);
//vertex.color = sf::Color(6525, 1111, 222, 255);
vertex.position = sf::Vector2f(x, y);
mutex.lock();
varray.append(vertex);
mutex.unlock();
}
}
}
效果很好。但是当我尝试使用线程加速进程时,我得到了一个不寻常的结果
void slicer(double left, double right, double top, double bottom, int slices)
{
int sliceSize = 800 / slices;
double start = 0, end = 0;
for (int i = 0; i < slices; i++)
{
start = i * sliceSize;
end = ((1 + i) * sliceSize);
thrd.push_back(thread(compute_mandelbrot, left, right, top, bottom, start, end));
}
for (int i = 0; i < slices; i++)
{
thrd[i].join();
}
thrd.clear();
}
如果我发送一个像这样的单一片段,现在这个奇怪的部分会伤到我的脑袋
compute_mandelbrot(left,right,top,bottom,400,480);
没有线程然后它工作正常,这就是为什么我很难理解为什么当我有线程渲染每个切片分开时,似乎有很多无色的位到处都是。
更奇怪的是,每次渲染的部分都是随机的,除了中间的一个切片(见图片),如果切片= 4,则永远不会有任何缺失的颜色
答案 0 :(得分:0)
我搬了
unsigned int colour = r | (r << 8) | (r << 16);
vertex.color = sf::Color(r, g, b, 255);
vertex.position = sf::Vector2f(x, y);
与varray.append(vertex)一起进入互斥体;它就像预期的那样工作