如何将全局数组传递给Web worker并返回它?

时间:2014-02-06 01:24:24

标签: javascript blob web-worker postmessage arraybuffer

最后30-40分钟我试图了解将数组传递给Web worker并将其返回的确切方法。目前我做了以下事情:

var myglobalarray = [1, 2, 3, 4, 5];
var code = 'self.addEventListener("message", function(e) {' + 
'  var receivedArray = e.data.buffer;' + 
'  var receivedArraysize = receivedArray.length;' + 
'  //doSomethinWithreceivedArray here...' + 
'  self.postMessage(receivedArray, [receivedArray]);' + 
'}, false);';
var blob = new Blob([code], {type: 'text/javascript'});
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);

worker.addEventListener('message', function(e) {
  var returnedArray = e.data;
  myglobalarray.length = 0;
  myglobalarray = e.data.slice();
}, false);

var passedArray = new ArrayBuffer(myglobalarray);
worker.postMessage(passedArray, [passedArray]);

但仍然获得了receivedArray is undefinedreceivedArray.length is undefined。任何想法问题在哪里?

1 个答案:

答案 0 :(得分:0)

一个简单的例子,数据是JSON序列化的

var blob = new Blob(["self.addEventListener('message', function(e) { postMessage(e.data); }, false);"]),
    blobURL = window.URL.createObjectURL(blob),
    worker = new Worker(blobURL);

worker.addEventListener('message', function (e) {
    console.log(e.data);
}, false);

worker.postMessage([1, 2, 3]);

jsFiddle

或许这就是你真正想要的,缓冲区被转移?你的头衔/问题不清楚。

var blob = new Blob(["self.addEventListener('message', function(e) { postMessage(e.data, [e.data]); }, false);"]),
    blobURL = window.URL.createObjectURL(blob),
    worker = new Worker(blobURL),
    myArray = [1, 2, 3, 4, 5],
    bufView = new Int8Array(myArray.length);

bufView.set(myArray);
worker.addEventListener('message', function (e) {
    console.log('transferred buffer in new view:', new Int8Array(e.data));
}, false);

worker.postMessage(bufView.buffer, [bufView.buffer]);
console.log('myArray - preserved:', myArray);
console.log('bufView - cleared by transfer:', bufView);

jsFiddle