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