web worker multithreading js

Solutions on MaxInterview for web worker multithreading js by the best coders in the world

showing results for - "web worker multithreading js"
Lucia
21 Apr 2017
1/** Options */
2var NUMBERS = 50000000;
3var WORKERS = 5; // NUMBERS should be divisble by WORKERS
4
5/** Goal: return sum of all numbers in array */
6var numbers = new Int8Array(NUMBERS);
7
8for(var i = 0; i < NUMBERS; i++){
9	numbers[i] = Math.floor(Math.random() * 100);
10}
11
12/** Test without web workers */
13var t0 = performance.now();
14var total = 0;
15for(var i = 0; i < numbers.length; i++){
16	total += numbers[i];
17}
18var t1 = performance.now();
19document.body.innerHTML += '<b>WITHOUT: </b>Total: ' + total + ' time: ' + (t1 - t0) + 'ms<br>';
20
21/** Test WITH web workers */
22var workers = [];
23
24var source = `
25onmessage = function(e) {
26  var array = new Int8Array(e.data.buffer);
27  var total = 0;
28	for(var i = 0; i < array.length; i++){
29  	total += array[i];
30  }
31  postMessage(total);
32}`
33
34for(var i = 0; i < WORKERS; i++){
35  var blob = new Blob([source]);
36  var blobURL = window.URL.createObjectURL(blob);
37  let worker = new Worker(blobURL);
38  
39  worker.onmessage = function(e){
40    total += e.data;
41    worker.terminate();
42    if(++finished == workers.length) done();
43  }
44  
45  workers.push(worker);
46}
47
48var finished = 0;
49var chunk = Math.floor(NUMBERS / WORKERS);
50
51var sliced = [];
52for(var i = 0; i < workers.length; i++){
53	sliced.push(numbers.slice(i*chunk,i*chunk+chunk));
54}
55
56var t0 = performance.now();
57console.log("workers started at", performance.now());
58var total = 0;
59for(var i = 0; i < workers.length; i++){
60  const data = {buffer: sliced[i].buffer};
61  workers[i].postMessage(data, [data.buffer]);
62}
63	
64function done(){
65	var t1 = performance.now();
66  document.body.innerHTML += '<b>WITH: </b>Total: ' + total + ' time: ' + (t1 - t0) + 'ms';
67}