HTML and CSS Reference
In-Depth Information
search : while ( myobj . foo < 200 ) {
myobj . foo += 1 ;
for ( var i = 2 ; i <= Math . sqrt ( myobj . foo ); i += 1 )
if ( myobj . foo % i == 0 )
continue search ;
// found a prime!
self . postMessage ( myobj );
}
// close this worker
self . close ();
};
The above code simply spits out prime numbers and ends at 200. You could set the while
loop to while(true) for endless output of prime numbers, but this is a simple example
to demonstrate how you can process data in chunks and parallelize the code to reach a
common goal with multiple worker threads.
From your main index.html (the place you want all the data to be displayed), initialize
your thread pool and give the workers a callback:
slidfast ({
workers : { script : 'worker1.js' , threads : 9 , mycallback : workerCallback }
});
To view a live demo of this technique, visit https://github.com/html5e/
slidfast/blob/master/example/workers/index.html .
When the workers parameter initializes, the following code creates the thread pool and
begins each task concurrently:
function Pool ( size ) {
var _this = this ;
// set some defaults
this . taskQueue = [];
this . workerQueue = [];
this . poolSize = size ;
this . addWorkerTask = function ( workerTask ) {
if ( _this . workerQueue . length > 0 ) {
// get the worker from the front of the queue
var workerThread = _this . workerQueue . shift ();
//get an index for tracking
slidfast . worker . obj (). index = _this . workerQueue . length ;
workerThread . run ( workerTask );
} else {
// no free workers,
_this . taskQueue . push ( workerTask );
Search WWH ::




Custom Search