Skip to content

Commit 9460758

Browse files
committed
feat: getting started example of worker_threads
1 parent 17f6387 commit 9460758

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const stringify = require('./json-util');
2+
3+
stringify({"uid": "10001"});
4+
stringify({"uid": "10002"});
5+
6+
/*
7+
输出日志如下,当 worker 通过 postMessage 给主线程发消息,1、父线程受到消息,并进入父线程的回调;2、父线程回调结束,子线程继续执行(postMessage后的逻辑)
8+
[main thread] before processing, process.pid = 61000, thread id = 0, uid = 10001
9+
[main thread] before processing, process.pid = 61000, thread id = 0, uid = 10002
10+
[worker thread] start processing, process id = 61000, thread id = 1, uid = 10001
11+
[main thread] message from worker[threadId = 1], process.pid = 61000, thread id = 0, uid = 10001
12+
[worker thread] start processing, process id = 61000, thread id = 2, uid = 10002
13+
[main thread] message from worker[threadId = 2], process.pid = 61000, thread id = 0, uid = 10002
14+
[worker thread] finishing processing, process id = 61000, thread id = 1, uid = 10001
15+
[worker thread] finishing processing, process id = 61000, thread id = 2, uid = 10002
16+
*/
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const {
2+
Worker, isMainThread, parentPort, workerData, threadId
3+
} = require('worker_threads');
4+
5+
if (isMainThread) {
6+
module.exports = function stringify(script) {
7+
console.log(`[main thread] before processing, process.pid = ${process.pid}, thread id = ${threadId}, uid = ${script.uid}`);
8+
return new Promise((resolve, reject) => {
9+
const worker = new Worker(__filename, {
10+
workerData: script
11+
});
12+
worker.on('message', (result) => {
13+
console.log(`[main thread] message from worker[threadId = ${result.threadId}], process.pid = ${process.pid}, thread id = ${threadId}, uid = ${script.uid}`);
14+
resolve(result)
15+
});
16+
worker.on('error', reject);
17+
worker.on('exit', (code) => {
18+
if (code !== 0)
19+
reject(new Error(`Worker stopped with exit code ${code}`));
20+
});
21+
});
22+
};
23+
} else {
24+
const threadId = require('worker_threads').threadId;
25+
console.log(`\t[worker thread] start processing, process id = ${process.pid}, thread id = ${threadId}, uid = ${workerData.uid}`);
26+
27+
function parse(jsonObj) {
28+
return JSON.stringify(jsonObj);
29+
}
30+
31+
const script = workerData;
32+
parentPort.postMessage({ jsonStr: parse(script), threadId: threadId } );
33+
34+
console.log(`\t[worker thread] finishing processing, process id = ${process.pid}, thread id = ${threadId}, uid = ${workerData.uid}`);
35+
}

0 commit comments

Comments
 (0)