1、run.js
const { Worker } = require('worker_threads')
const configs = require('../../config/config').config
const pass_share = new SharedArrayBuffer(4)
const failed_share = new SharedArrayBuffer(4)
const status = new SharedArrayBuffer(4)
const on_off = new Int32Array(status)
let workerNum = configs.worker_num
let countNum = configs.childworker_num
Atomics.store(on_off,0,0);
let start_time;
let failedCount;
let successCount;
for (let i = 0; i < workerNum; i++) {
const worker = new Worker('./check_text/text.js')
if(i === (workerNum-1)){
start_time = new Date().getTime();
Atomics.store(on_off,0,1)
}
worker.postMessage({'id': worker.threadId, 'pass': pass_share, 'failed': failed_share,time:on_off})
worker.on('message', function (msg) {
successCount = msg.passCount[0];
failedCount = msg.failedCount[0]
if (msg.signal === 'exit') {
console.log('线程' + msg.id + ':' + msg.str + ',成功:' + msg.passCount[0] + ',失败:' + msg.failedCount[0])
worker.terminate()
} else {
console.log('线程' + msg.id + ':' + msg.str + ',成功:' + msg.passCount[0] + ',失败:' + msg.failedCount[0])
}
})
}
process.on('exit', function (code){
let end_time = new Date().getTime();
console.table({
'运行时长' : (end_time - start_time)/1000 + "s",
'工作线程' : workerNum,
'请求总数' : workerNum*countNum,
'请求成功' : successCount,
'请求失败' : failedCount,
'每秒并发' : Math.floor(workerNum*countNum/((end_time - start_time)/1000))
})
})
text.js
const { parentPort } = require('worker_threads')
const axios = require('axios')
const configs = require('../../config/config').config
const random_text = require('../../utils/random_text')
parentPort.on('message', async function (msg) {
let passCount = new Int32Array(msg.pass)
let failedCount = new Int32Array(msg.failed)
let countNum = configs.childworker_num
if(msg.time[0] === 0){
Atomics.wait(msg.time,0)
}
else {
Atomics.notify(msg.time,0)
}
for (let i = 0; i < countNum; i++) {
let data =
{
"contextId": "",
"textContent": random_text,
"policies": [
{
"type": "keyword",
"policyId": 174,
"info": ""
}
],
"returnSummary": true
}
await axios.post('http://***.com',
data)
.then(res => {
if (res.data.code !== '0000') {
Atomics.add(failedCount, 0, 1)
} else {
Atomics.add(passCount, 0, 1)
}
}).catch(error => {
Atomics.add(failedCount, 0, 1)
})
if (i !== (countNum - 1)) {
parentPort.postMessage({
'id': msg.id,
'str': `第${ i + 1 }次运行`,
'passCount': passCount,
'failedCount': failedCount
})
} else {
parentPort.postMessage({
'signal': 'exit',
'id': msg.id,
'str': `第${i + 1}次运行`,
'passCount': passCount,
'failedCount': failedCount
})
}
}
})
3、结果如图