-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultiThreads.js
99 lines (90 loc) · 2.29 KB
/
multiThreads.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* @Author: Alfred Yang
* @Github: https://github.com/cat-walk
* @Date: 2019-08-17 16:59:21
* @LastEditors: Alfred Yang
* @LastEditTime: 2019-08-19 17:13:14
* @Description: file content
*/
const EventEmitter = require('events');
const puppeteer = require('puppeteer');
const {
isMainThread,
parentPort,
workerData,
threadId,
MessageChannel,
MessagePort,
Worker
} = require('worker_threads');
const testPage = require('./testPage');
const {
run,
saveData,
getAverage,
getMetricTPGroup,
judgeIsMeaningfulSample
} = require('./utils');
process.env.UV_THREADPOOL_SIZE = 128;
EventEmitter.defaultMaxListeners = 100;
let allData = [];
let stopedWorker = 0;
const totalTime = 1000;
const threadNum = 10;
const pagesPerBrowser = 10;
const timeOfABrowser = totalTime;
const work = async browser => {
const page = await browser.newPage();
const dataOfASample = await testPage(page);
// console.log('dataOfASample', dataOfASample);
await page.close();
const isMeaningfulSample = judgeIsMeaningfulSample(dataOfASample);
if (isMeaningfulSample) {
allData.push(dataOfASample);
}
};
const workOfABrowser = async () => {
const browser = await puppeteer.launch();
await run(work.bind(null, browser), pagesPerBrowser, timeOfABrowser);
await browser.close();
};
const workerExitListner = async code => {
console.log(`main: worker stopped with exit code ${code}`);
stopedWorker++;
console.log('stopedWorker', stopedWorker);
if (stopedWorker === threadNum) {
const average = await getAverage(allData);
const MetricTPGroup = getMetricTPGroup(allData);
await saveData(
JSON.stringify({
id: 0,
allData,
MetricTPGroup,
average
}),
'./multi-threads-data.json'
);
}
};
const msgListner = msg => {
// console.log('msg', msg);
allData = allData.concat(msg);
// console.log('totalData.length', totalData.length);
};
async function mainThread() {
for (let i = 0; i < threadNum; i++) {
const worker = new Worker(__filename);
worker.on('exit', workerExitListner);
worker.on('message', msgListner);
}
}
async function workerThread() {
await workOfABrowser(allData);
await parentPort.postMessage(allData);
// console.log('workerData', workerData);
}
if (isMainThread) {
mainThread();
} else {
workerThread();
}