Skip to content

Instantly share code, notes, and snippets.

@roman01la
Created May 7, 2016 20:28
Show Gist options
  • Save roman01la/3fd3e0a31538fb4fbf33ee372c248e49 to your computer and use it in GitHub Desktop.
Save roman01la/3fd3e0a31538fb4fbf33ee372c248e49 to your computer and use it in GitHub Desktop.
'use strict';
(function() {
const shmem = new SharedArrayBuffer(1024 * 100000); // 25600000
const sync = new Int32Array(shmem);
const cores = [...new Array(navigator.hardwareConcurrency)];
const sync_shift = cores.length;
const core_shift = (sync.length - sync_shift) / sync_shift;
let doneCount = 0;
console.time('main thread')
for (let i = 0, ln = sync.length; i < ln; i++) {
sync[i] = Math.round(Math.random() * 100);
}
console.timeEnd('main thread')
cores
.map((core, idx) => {
const worker = new Worker('/js/worker.js');
worker.postMessage([shmem, idx, sync_shift, core_shift], [shmem]);
worker.onmessage = ({ data }) => {
if (data === 'done') {
doneCount++;
if (doneCount === sync_shift) {
console.timeEnd(sync_shift + ' workers')
}
}
};
return worker;
})
.forEach((worker, idx) => {
if (idx === 0) {
console.time(sync_shift + ' workers')
}
Atomics.store(sync, idx, 1);
Atomics.wake(sync, idx, 1);
});
})();
'use strict';
onmessage = ({ data }) => runWorker(...data);
function runWorker(shmem, idx, sync_shift, core_shift) {
const sync = new Int32Array(shmem);
while (true) {
Atomics.wait(sync, idx, 0);
Atomics.store(sync, idx, 0);
for (let i = core_shift * idx + sync_shift; i < core_shift * (idx + 1) + sync_shift; i++) {
sync[i] = Math.round(Math.random() * 100);
}
postMessage('done');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment