Mandelbrot using Web Workers and Canvas
Categories: Technical

I recently entered a contest to write a JavaScript program that did something interesting with HTML5 in less than 10 kilobytes, including HTML and CSS files. I decided to do a program that calculates the Mandelbrot set using Web Workers and displays the results using Canvas. I had originally written a C program that calculates the set when I was an undergrad, and also at that time I wrote a multi-threaded version using pthreads, and a distributed version in C using MPI. More recently I wrote a version in Clojure using agents. For the contest I wrote a solution in JavaScript using Web Workers.

The algorithm to calculate the Mandelbrot set is known as embarrassingly parallel, since it is obvious how to parallelize the sequential algorithm since each pixel can be calculated independent of the other pixels. Each worker is given a number of columns of the image to calculate as a message. Upon completion of the calculation it posts a message back. The master collects these messages and uses Canvas to draw a 2D image of the result. Web Workers are not threads, and there is no shared data, everything is done using message passing.

I tested this in Firefox 3.5, Safari 5.0, and Chrome 5.0. Firefox is interesting in that the messages from the workers come back in the same order as the workers were fired, so essentially no two workers ever operate in parallel and no speedup is gained over the sequential version, in fact it runs slower because of the communication overhead. Safari will launch a seemingly unbounded number of workers, and you can easily crash it by drawing a large image and matching the number of workers with the image. Chrome limits the number of workers to a total of 16, and no error message displays if the program attempts to launch more.

The source is here on GitHub and here is a link to the entry.

Categories: Technical - Tags: , ,

Leave a Reply