Skip to main content

Move

Piscina provides a move() function that allows the transfer of data between the main thread and worker threads. The example below will show you how to use Piscina.move() to transfer ArrayBuffer without cloning, which can significantly improve performance for large data transfers.

index.js
const Piscina = require('piscina');
const { resolve } = require('path');

const pool = new Piscina({
filename: resolve(__dirname, 'worker.js'),
idleTimeout: 1000
});

(async () => {
// The task will transfer an ArrayBuffer
// back to the main thread rather than
// cloning it.
const u8 = await pool.run(Piscina.move(new Uint8Array(2)));
console.log(u8.length);
})();

The worker file uses move() to transfer data back to the main thread:

worker.js
const { move } = require('piscina');

module.exports = () => {
// Using move causes the Uint8Array to be
// transferred rather than cloned.
return move(new Uint8Array(10));
};

You can also check out this example on github.