工作线程未在 Node.js 中运行

问题描述

我正在尝试使用限制为 10 个线程的工作线程来实现基本矩阵乘法。但是不是工作线程的线程根本没有响应。 矩阵 A 和 B 填充随机生成器。

if (isMainThread) {
    const M = 100;
    const N = 100;

    const matrixA = [];
    for (let i = 1; i <= M; i++) {
        // random numbers for each element of mat A
    }

    const matrixB = [];
    for (let i = 1; i <= M; i++) {
        // random numbers for each element of mat B
    }

    let matCCount = 0;
    const totalCount = (M * N);
    const matrixC = [];
    const time1 = new Date();

    let threadCount = 0;

    const calculateResult = (matrixC) => {
        const time2 = new Date();
        console.log(`\nTime taken: ${(time2 - time1) / 1000}s`);
    }

    const mainService = function(getResult) {
        for (let i = 0; i < M; i++) {
            for (let j = 0; j < N; j++) {
                let success = false;
                do {
                    if (threadCount < 11) {
                        const worker = new Worker(__filename,{ workerData: { i,j,matrixA,matrixB } });
                        threadCount ++;
                        worker.on('message',(message) => {
                            getResult(message);
                            success = true;
                            threadCount --;
                        });
                        worker.on('online',() => { console.log('online'); })
                        worker.on('error',(err) => {
                            console.log(err);
                        });
                        worker.on('exit',(code) => { console.log(code); })
                    }
                } while (!success);
            }
        }
    }
    mainService((res) => {
        const { i,result } = res;
        if (matrixC[i] === undefined) {
            matrixC[i] = [];
        }
        matrixC[i][j] = result;
        matCCount += 1;
        if (matCCount === totalCount) {
            calculateResult(matrixC);
        }
    });
} else {
    const { i,matrixB } = workerData;
    const x = multiplyOperation(i,matrixB);
    parentPort.postMessage({ i,result: x,threadId });
}

'online' 事件既不会被触发,也不会运行这个 console.log

} else {
    console.log(threadId);
    const { i,threadId });
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)