web workers multithreading code example

Example: web worker multithreading js

/** Options */
var NUMBERS = 50000000;
var WORKERS = 5; // NUMBERS should be divisble by WORKERS

/** Goal: return sum of all numbers in array */
var numbers = new Int8Array(NUMBERS);

for(var i = 0; i < NUMBERS; i++){
	numbers[i] = Math.floor(Math.random() * 100);
}

/** Test without web workers */
var t0 = performance.now();
var total = 0;
for(var i = 0; i < numbers.length; i++){
	total += numbers[i];
}
var t1 = performance.now();
document.body.innerHTML += '<b>WITHOUT: </b>Total: ' + total + ' time: ' + (t1 - t0) + 'ms<br>';

/** Test WITH web workers */
var workers = [];

var source = `
onmessage = function(e) {
  var array = new Int8Array(e.data.buffer);
  var total = 0;
	for(var i = 0; i < array.length; i++){
  	total += array[i];
  }
  postMessage(total);
}`

for(var i = 0; i < WORKERS; i++){
  var blob = new Blob([source]);
  var blobURL = window.URL.createObjectURL(blob);
  let worker = new Worker(blobURL);
  
  worker.onmessage = function(e){
    total += e.data;
    worker.terminate();
    if(++finished == workers.length) done();
  }
  
  workers.push(worker);
}

var finished = 0;
var chunk = Math.floor(NUMBERS / WORKERS);

var sliced = [];
for(var i = 0; i < workers.length; i++){
	sliced.push(numbers.slice(i*chunk,i*chunk+chunk));
}

var t0 = performance.now();
console.log("workers started at", performance.now());
var total = 0;
for(var i = 0; i < workers.length; i++){
  const data = {buffer: sliced[i].buffer};
  workers[i].postMessage(data, [data.buffer]);
}
	
function done(){
	var t1 = performance.now();
  document.body.innerHTML += '<b>WITH: </b>Total: ' + total + ' time: ' + (t1 - t0) + 'ms';
}