worker.markAsUntransferable(object)
将对象标记为不可传输。
如果 object
出现在 port.postMessage()
调用的传输列表中,则忽略它。
特别是,这对于可以克隆而不是传输的对象,以及被发送方的其他对象使用的对象来说是有意义的。
例如,Node.js 用这个标记了它用于 Buffer
池的 ArrayBuffer
。
此操作无法撤消。
const { MessageChannel, markAsUntransferable } = require('node:worker_threads');
const pooledBuffer = new ArrayBuffer(8);
const typedArray1 = new Uint8Array(pooledBuffer);
const typedArray2 = new Float64Array(pooledBuffer);
markAsUntransferable(pooledBuffer);
const { port1 } = new MessageChannel();
port1.postMessage(typedArray1, [ typedArray1.buffer ]);
// 以下行打印 typedArray1 的内容,
// 它仍然拥有它的内存并且已经被克隆,而不是传输。
// 没有 `markAsUntransferable()`,这将打印空的 Uint8Array。
// typedArray2 也完好无损。
console.log(typedArray1);
console.log(typedArray2);
浏览器中没有与此 API 等效的 API。
Mark an object as not transferable. If object
occurs in the transfer list of
a port.postMessage()
call, it is ignored.
In particular, this makes sense for objects that can be cloned, rather than
transferred, and which are used by other objects on the sending side.
For example, Node.js marks the ArrayBuffer
s it uses for its
Buffer
pool with this.
This operation cannot be undone.
const { MessageChannel, markAsUntransferable } = require('node:worker_threads');
const pooledBuffer = new ArrayBuffer(8);
const typedArray1 = new Uint8Array(pooledBuffer);
const typedArray2 = new Float64Array(pooledBuffer);
markAsUntransferable(pooledBuffer);
const { port1 } = new MessageChannel();
port1.postMessage(typedArray1, [ typedArray1.buffer ]);
// The following line prints the contents of typedArray1 -- it still owns
// its memory and has been cloned, not transferred. Without
// `markAsUntransferable()`, this would print an empty Uint8Array.
// typedArray2 is intact as well.
console.log(typedArray1);
console.log(typedArray2);
There is no equivalent to this API in browsers.