Skip to content

Commit

Permalink
feat: getting started example of worker_threads
Browse files Browse the repository at this point in the history
  • Loading branch information
chyingp committed Mar 24, 2022
1 parent 17f6387 commit 9460758
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
16 changes: 16 additions & 0 deletions examples/2022.03.24-worker-threads/getting-started/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const stringify = require('./json-util');

stringify({"uid": "10001"});
stringify({"uid": "10002"});

/*
输出日志如下,当 worker 通过 postMessage 给主线程发消息,1、父线程受到消息,并进入父线程的回调;2、父线程回调结束,子线程继续执行(postMessage后的逻辑)
[main thread] before processing, process.pid = 61000, thread id = 0, uid = 10001
[main thread] before processing, process.pid = 61000, thread id = 0, uid = 10002
[worker thread] start processing, process id = 61000, thread id = 1, uid = 10001
[main thread] message from worker[threadId = 1], process.pid = 61000, thread id = 0, uid = 10001
[worker thread] start processing, process id = 61000, thread id = 2, uid = 10002
[main thread] message from worker[threadId = 2], process.pid = 61000, thread id = 0, uid = 10002
[worker thread] finishing processing, process id = 61000, thread id = 1, uid = 10001
[worker thread] finishing processing, process id = 61000, thread id = 2, uid = 10002
*/
35 changes: 35 additions & 0 deletions examples/2022.03.24-worker-threads/getting-started/json-util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const {
Worker, isMainThread, parentPort, workerData, threadId
} = require('worker_threads');

if (isMainThread) {
module.exports = function stringify(script) {
console.log(`[main thread] before processing, process.pid = ${process.pid}, thread id = ${threadId}, uid = ${script.uid}`);
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, {
workerData: script
});
worker.on('message', (result) => {
console.log(`[main thread] message from worker[threadId = ${result.threadId}], process.pid = ${process.pid}, thread id = ${threadId}, uid = ${script.uid}`);
resolve(result)
});
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
});
};
} else {
const threadId = require('worker_threads').threadId;
console.log(`\t[worker thread] start processing, process id = ${process.pid}, thread id = ${threadId}, uid = ${workerData.uid}`);

function parse(jsonObj) {
return JSON.stringify(jsonObj);
}

const script = workerData;
parentPort.postMessage({ jsonStr: parse(script), threadId: threadId } );

console.log(`\t[worker thread] finishing processing, process id = ${process.pid}, thread id = ${threadId}, uid = ${workerData.uid}`);
}

0 comments on commit 9460758

Please sign in to comment.