Skip to content

What is the correct way to ensure zero copy of an ArrayBuffer and the ability to transfer back to the main thread (without reassignment) #385

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
CMCDragonkai opened this issue Jul 16, 2021 · 1 comment
Labels

Comments

@CMCDragonkai
Copy link

CMCDragonkai commented Jul 16, 2021

I have a worker function:

  mutate (what: ArrayBuffer): TransferDescriptor<ArrayBuffer> {
    const inView = new Uint8Array(what);
    inView[0] = 88;
    return Transfer(what);
  },

When I Transfer an ArrayBuffer into this method, the original ArrayBuffer becomes detached.

  const what = await workerManager.call(
    async w => {
      const o = await w.mutate(Transfer(ab));
      return o;
    }
  );
ab => ArrayBuffer { (detached), byteLength: 0 }
what => ArrayBuffer { [Uint8Contents]: <58 62 63>, byteLength: 3 }

Note that the call method just does this:

  public async call<T>(
    f: (worker: ModuleThread<EFSWorker>) => Promise<T>,
  ): Promise<T> {
    if (!this.pool) {
      throw new workersErrors.EncryptedFSWorkerNotRunningError();
    }
    return await this.pool.queue(f);
  }

I notice I have to use the returned array buffer. The ab is no longer usable.

I thought I would be able to share a buffer with a thread, make that thread make mutations, and then share that buffer back, but the above seems to mean that I have to use a new assignment, and discard the old assignment.

Furthermore I actually want to use Node buffers. But when I use node buffers with the internal array buffer, the internal array buffer gets detached even under the same usage. This is quite strange behaviour.

This is a follow up from #348

@CMCDragonkai CMCDragonkai changed the title What is the correct way to ensure zero copy and the ability to transfer back What is the correct way to ensure zero copy of an ArrayBuffer and the ability to transfer back to the main thread (without reassignment) Jul 16, 2021
@andywer
Copy link
Owner

andywer commented Jul 16, 2021

Please check out my answer in #348. I think it covers that topic as well.

I wonder if there should be a package with serializers for commonly used data types like Buffers. We cannot really add it to threads.js itself, though, as that will not work in browsers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants