Junior — Middle
Have you had experience working with shared memory in your projects?
sobes.tech AI
Answer from AI
Yes, in Node.js projects, there is sometimes a need to use shared memory for data exchange between processes or threads, especially when working with worker_threads.
Node.js provides the worker_threads module, where you can use SharedArrayBuffer to create shared memory. This allows multiple threads to read and write to the same memory area without copying data.
Example of using SharedArrayBuffer:
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const sharedBuffer = new SharedArrayBuffer(4); // 4 bytes
const sharedArray = new Int32Array(sharedBuffer);
sharedArray[0] = 0;
const worker = new Worker(__filename, { workerData: sharedBuffer });
worker.on('exit', () => {
console.log('Value in main thread:', sharedArray[0]);
});
} else {
const { workerData } = require('worker_threads');
const sharedArray = new Int32Array(workerData);
Atomics.add(sharedArray, 0, 10); // atomically increase the value
parentPort.close();
}
This approach is useful for high-performance applications where minimizing overhead for data copying between threads is important.