dimanche 25 juin 2017

SharedArrayBuffer and SharedWorker

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.




Aucun commentaire:

Enregistrer un commentaire