Hi @flodeux,
Sorry for the late answer
The Processing thread()
function is a wrapper for easily creating a Thread
instance that launches a method defined earlier. (see the actual code here).
What you need to do is to break your image into square tiles, one for each thread, do the computation of each specific tile and then wait for all the threads to finish.
This is an example by extending the Thread
class and assigning a random color for each time:
class TileThread extends Thread {
int x, y, w, h;
color randomColor;
TileThread(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
randomColor = color(random(255), random(255), random(255));
}
void run() {
for (int i = x; i < x + w; i++) {
for (int j = y; j < y + h; j++) {
int loc = i + width * j;
pixels[loc] = randomColor;
}
}
}
}
int nTiles = 5;
void setup() {
size(500, 500);
}
void draw() {
int tileSizeX = width / nTiles;
int tileSizeY = height / nTiles;
ArrayList<Thread> tileThreads = new ArrayList();
loadPixels();
// Create one thread for each square tile (like a grid)
for (int i = 0; i < nTiles; i++) {
int x = i * tileSizeX;
for (int j = 0; j < nTiles; j++) {
int y = j * tileSizeY;
Thread thread = new TileThread(x, y, tileSizeX, tileSizeY);
thread.run();
tileThreads.add(thread);
}
}
// Wait for all the threads to finish
for (Thread thread : tileThreads) {
try {
thread.join();
} catch (InterruptedException e) {
println(e);
}
}
updatePixels();
}
(this works when the canvas size is divisible by nTiles
but you can support non square tiles)
(be careful not to modify the same tiles from two different threads leading to a race condition)