js share array between thread

Viewed 90

I try to make threads is js, 1 thread will read a file and push words into an array, 2nd thread will read the array and console.log the word.

enter image description here

I didn't find any solutions except using worker_threads.

This is my main file:

var data = [];
var i = 0;
var finish = false;

function runWorker() {
    const worker = new Worker('./worker.js', { workerData: { i, data } });
    const worker2 = new Worker('./worker2.js', { workerData: { i, data, finish } });

    worker.on('message', function(x) {
        data.push[x.data]
        if(x.finish != undefined){
            finish = true
        }
    });

    worker.on('error', function(error) {
        console.log(error);
    });

    worker2.on('message', function(x) {
        console.log(x)
    });

    worker2.on('error', function(error) {
        console.log(error);
    });
    
    worker.on('exit', code => {
        if (code !== 0) console.log(new Error(`Worker stopped with exit code ${code}`));
    });
}

runWorker();

this is my worker.js file :

const { workerData, parentPort } = require('worker_threads');
var fs = require('fs');
const chalk = require('chalk');


fs.readFile('./input.txt', async function read(err, data) {
    if (err) {
        console.log(' |-> ' + chalk.bold.red("impossible a lire"))
    }
    else{
        console.log(' |-> ' + chalk.blue("début lecture du fichier"))
        data = data.toString().split(" ");
        for(var i = 0; i<data.length; i++){
            parentPort.postMessage({data:data[i]})
        }
        parentPort.postMessage({finish:true})
    }
})

Here I read a file, and send each word to the main programme to put it into an array

this is my worker2.js file :

const { workerData, parentPort } = require('worker_threads');

let finish = false

while(!finish){
    let data = workerData.data;
    let i = workerData.i;
    finish = workerData.finish;
    console.log(data[i]);
}

Here I have an infinite loop, and if something is on the array, print it.

0 Answers
Related