代码之家  ›  专栏  ›  技术社区  ›  joe

与工作人员共享SharedArray缓冲区的TypedArray视图-是否可以访问完整的SharedArray缓冲区时?

  •  0
  • joe  · 技术社区  · 2 年前

    如果我创建 SharedArrayBuffer ,然后通过 TypedArray ,然后发送 类型阵列 Worker 通过 postMessage ,工作人员是否能够访问的完整数据 类型阵列 ?

    1 回复  |  直到 2 年前
        1
  •  0
  •   joe    2 年前

    是的,整个底层缓冲区与web工作者共享:

    <!-- test.html -->
    <script>
      // Main thread
      const sharedBuffer = new SharedArrayBuffer(100); 
      const fullBuffer = new Uint8Array(sharedBuffer);
      fullBuffer.set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // Fill the start of the buffer with some data
      const partOfBuffer = new Uint8Array(sharedBuffer, 5); // Create a view that leaves off the first few numbers
    
      const worker = new Worker('worker.js');
      worker.postMessage(partOfBuffer);
    </script>
    
    // worker.js
    onmessage = function(e) {
      const partOfBuffer = e.data;
      console.log(new Uint8Array(partOfBuffer.buffer)); // logs the full buffer data - i.e. including the first few numbers
    }
    
    推荐文章