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.
- Javascript
- Typescript
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);
})();
index.ts
import Piscina from 'piscina';
import { resolve } from 'path';
const pool = new Piscina({
filename: resolve(__dirname, 'worker.ts'),
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:
- Javascript
- Typescript
worker.js
const { move } = require('piscina');
module.exports = () => {
// Using move causes the Uint8Array to be
// transferred rather than cloned.
return move(new Uint8Array(10));
};
worker.ts
import { resolve } from "path";
import { move } from "piscina";
export const filename = resolve(__filename);
export default (): Uint8Array => {
// Using move causes the Uint8Array to be
// transferred rather than cloned.
return move(new Uint8Array(10)) as Uint8Array;
};
You can also check out this example on github.