当我确实需要在工作人员内部使用(“web3”)时,我面临一个问题。我有一个主线程,它在每个调用中创建3个工人。每个工人都在使用require('web3')。主线程也在使用require('web3')
它适用于对程序的第一次调用,但nodejs在对程序的第二次调用时崩溃。奇怪的是,当我在主线程中使用require('web3')时,就会出现这个问题。我无法避免这一点,因为我也需要在主线程中使用web3。
是否有更新require缓存的问题?
express = require('express');
bodyParser = require('body-parser');
var Web3 = require('web3')
app = express();
path = require('path')
const {
Worker, MessageChannel, MessagePort, isMainThread, parentPort
} = require('worker_threads');
const port = 8080;
app.listen(port, () => {
console.log(`Server running on port${port}`);
});
app.get("/test", function(req, res) {
(async() => {
await test();
})();
});
async function test() {
console.log("\n\n***starting threads***\n\n");
return new Promise((parentResolve, parentReject) => {
threadCount = 2;
const promises = [];
for (let idx = 0; idx < threadCount; idx += 1) {
var testdata = {};
testdata.id = idx+1;
//testdata.web3 = web3;
promises.push(new Promise((resolve, reject) => {
var worker = null;
try {
worker = new Worker("./scripts/workers/testworker.js", {
workerData: testdata});
} catch(err) {
console.log(err);
}
worker.on("exit", () => {
console.log("Worker exiting");
resolve()
});
worker.on("message", (result) => {
console.log(result);
});
worker.on("error", (result) => {
console.log(result);
});
}).catch(error => {
console.log(error);
parentReject(error);
}));
}
return Promise.all(promises).then(() => {
console.log("\n\n***Ending threads***\n\n");
parentResolve("");
});
});
}
工人代码如下所示
web3 = require('web3');
Tx = require('ethereumjs-tx').Transaction;
const { Worker, parentPort, workerData } = require("worker_threads");
parentPort.postMessage("inside worker : " + workerData.id);
暂无答案!
目前还没有任何答案,快来回答吧!