Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using an iframe as a worker
<!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
You can’t perform that action at this time.