I'm implementing a program that calculates a Julia set. It will use multiple threads, depending on how many processors are available. Each thread calculates a line, but only when that line is not being calculated by another thread. This part WORKS pretty well.
But sometimes when I test it with bigger images (more lines to calculate, for example instead of getHeight() = 1200
, I set it to 3000
, there are some lines which are skipped). I want to make it more secure, so that no line will be calculated twice, and no lines will be skipped. Here is the code of the run()
method:
public void run() {
while (counter < getHeight()-1) {
synchronized(this) {
if (counter >= getHeight() -1) { //so that the last line will not be calculated >2 times.
return;
}
counter++;
image.setRGB(0, counter, getWidth(), 1, renderLine(counter), 0, 0);
}
}
}
I want it to work like that: if the current line is being calculated, the thread goes to the next line.. without that it get confused, so that lines get skipped..
I'm trying this actually:
public void run() {
while (counter < getHeight()-1 && !working) {
synchronized(this) {
working = true;
if (counter >= getHeight() -1) { //so that the last line will not be calculated >2 times.
return;
}
counter++;
image.setRGB(0, counter, getWidth(), 1, renderLine(counter), 0, 0);
working = false;
}
}
}
but I don't know if it will prevent access to another thread, while a thread is already working, and it will change the value of "counter", meaning that lines can be skipped!
Do I need a boolean variable to notify that a thread is actually working on a line? Any advice?