I need to draw the Mandelbrot set using parallel programming, the language used is Java. I employ Runnable tasks to do that. As setRGB is synchronized, I don't need locks to control concurrency and also the BufferedImage shared between all threads is accessed in parallel so it should not be a problem of concurrency. Here is the code below:
public class MandelParalelo extends JFrame
implements Runnable{
private final int MAX_ITER = 100000;
private final double ZOOM = 150;
private static BufferedImage Imagen;
private double zx, zy, cX, cY, tmp;
private int nTareas = 6;
private int linf, lsup;
public void run()
{
for (int y = linf; y < lsup; y++) {
for (int x = 0; x < getWidth(); x++) {
zx = zy = 0;
cX = (x - 400) / ZOOM;
cY = (y - 300) / ZOOM;
int iter = MAX_ITER;
while (zx * zx + zy * zy < 4 && iter > 0) {
tmp = zx * zx - zy * zy + cX;
zy = 2.0 * zx * zy + cY;
zx = tmp;
iter--;
}
Imagen.setRGB(x, y, iter | (iter << 8));//setRGB es synchronized
}
}
}
public MandelParalelo(int i, int s)
{
linf = i;
lsup = s;
}
public MandelParalelo() {
super("Conjunto de Mandelbrot");
setBounds(100, 100, 800, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Imagen = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_RGB);
ExecutorService ejecutor = Executors.newFixedThreadPool(8);
int inf = 0, tVentana = getHeight()/nTareas, sup = tVentana;
for(int i = 0; i < nTareas; i++)
{
ejecutor.execute(new MandelParalelo(inf, sup));
inf = sup;
sup += tVentana;
}
ejecutor.shutdown();
while(!ejecutor.isTerminated()){}
}
public void paint(Graphics g) {
g.drawImage(Imagen, 0, 0, this);
}
public static void main(String[] args) {
new MandelParalelo().setVisible(true);
}
}