Created
October 24, 2017 17:31
-
-
Save dpino/0e2eb8249f55efb29e06e1d587103e50 to your computer and use it in GitHub Desktop.
Using an iframe as a worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title></title> | |
</head> | |
<body> | |
<iframe id="w0" src="iframe2.html" style="display: none"></iframe> | |
<script type="text/javascript"> | |
window.addEventListener('load', function(e) { | |
function getIFrames() { | |
var ret = []; | |
var elements = document.getElementsByTagName('iframe'); | |
for (let i = 0; i < elements.length; i++) { | |
ret.push(elements[i].contentWindow); | |
} | |
return ret; | |
} | |
function broadcast(workers, sab, idx) { | |
for (w of workers) { | |
w.postMessage([sab, idx], '*'); | |
} | |
} | |
var workers = getIFrames(); | |
workers[0].onmessage = function(e) { | |
var sab = e.data[0]; | |
var ia = new Int32Array(sab); | |
// FIXME: Returns 'invalid array type for the operation'. | |
// If I instantiate a new Int32Array(SharedArrayBuffer) and used in Atomics.wait, it says: | |
// 'waiting is not allowed on this thread'. | |
var ret = Atomics.wait(ia, 0, 0, 1000); | |
window.postMessage(ret, '*'); | |
}; | |
window.onmessage = function(e) { | |
// FIXME: Should return 'ok'. | |
console.log(e.data); | |
} | |
var ia = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)); | |
broadcast(workers, ia.buffer); | |
setTimeout(() => Atomics.wake(ia, 0, 1), 500); // Wake one | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment