Reputation: 11
In the features of ECMAScript 2017 there is Shared memory and atomics. I try test it in Google Chrome 59.0.3071.109 (Experimental SharedArrayBuffer flag is enabled). When I try post SharedArrayBuffer in simple Worker it's works. But when I try post SharedArrayBuffer in SharedWorker, in event parament of onmessage event handler I get event.data is null. Why is this so? Here is an example of my code:
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web Workers</title>
<script src="main.js"></script>
</head>
<body>
<button onclick="post()">Post</button>
<button onclick="get()">Get</button>
</body>
</html>
main.js:
var worker = new SharedWorker('worker.js');
var buffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
new Int32Array(buffer)[0] = 12;
function post() {
worker.port.postMessage({buffer});
}
function get() {
console.log(new Int32Array(buffer)[0]);
}
worker.js:
self.onconnect = function (e) {
var [port] = e.ports;
port.onmessage = function (e) {
console.log(e.data);// null
};
};
Thank you.
Upvotes: 1
Views: 1346
Reputation: 31
According Chromium Blink Workers Documention: Shared Worker is Out-of-process.
It run on another system process different to document process(which contain JS mainthread).
Operation System process deny memory access from other process.
SharedArraybuffer
work by share(access) memory. So SharedArraybuffer
create(access) by JS mainthread(document process) can't access by Shared Worker
(Out-of-process).
Upvotes: 2