File tree Expand file tree Collapse file tree 4 files changed +63
-0
lines changed
Expand file tree Collapse file tree 4 files changed +63
-0
lines changed Original file line number Diff line number Diff line change 1+ import { Worker , isMainThread , parentPort } from "node:worker_threads" ;
2+
3+ if ( isMainThread ) {
4+ const CPU_core = 10 ;
5+ for ( let i = 0 ; i < CPU_core ; i ++ ) {
6+ // Create a new worker thread
7+ const worker = new Worker ( "./worker.js" ) ;
8+ // pass value to the worker thread
9+ worker . postMessage ( [
10+ `Thread-${ i + 1 } ` ,
11+ Math . ceil ( Math . random ( ) * 10 ) * 1000000000 ,
12+ ] ) ;
13+ // Listen for messages from the worker thread
14+ worker . on ( "message" , ( result ) => {
15+ console . log ( `${ result } is done.` ) ;
16+ worker . terminate ( ) ; // Terminate the worker thread
17+ } ) ;
18+ // Handle errors in the worker thread
19+ worker . on ( "error" , ( err ) => {
20+ console . error ( `Worker error: ${ err } ` ) ;
21+ } ) ;
22+ }
23+ console . log ( "waiting to complete...." ) ;
24+ } else {
25+ // This code is executed in the as worker thread mode
26+ parentPort . on ( "message" , ( message ) => {
27+ console . log ( `Received message from Other thread: ${ message } ` ) ;
28+ // Perform some task (in this case, just echoing the message)
29+ parentPort . postMessage ( `Hello from worker! Received: ${ message } ` ) ;
30+ } ) ;
31+ }
Original file line number Diff line number Diff line change 1+ {
2+ "name" : " coworker-thread" ,
3+ "version" : " 1.0.0" ,
4+ "main" : " Main.js" ,
5+ "scripts" : {
6+ "test" : " echo \" Error: no test specified\" && exit 1"
7+ },
8+ "type" : " module" ,
9+ "author" : " jaydatt" ,
10+ "license" : " ISC" ,
11+ "description" : " "
12+ }
Original file line number Diff line number Diff line change 1+ import { parentPort } from "worker_threads" ;
2+
3+ function performTask ( n ) {
4+ let result = 0 ;
5+ for ( let i = 0 ; i <= n ; i ++ ) {
6+ result += i ;
7+ // console.log(i);
8+ }
9+ }
10+
11+ // Listen for messages from the parent thread
12+ parentPort . on ( "message" , ( arr ) => {
13+ console . log ( `Received from parent thread: ${ arr } ` ) ;
14+
15+ // Perform the task
16+ performTask ( arr [ 1 ] ) ;
17+
18+ // Send the result back to the parent thread
19+ parentPort . postMessage ( arr [ 0 ] ) ;
20+ } ) ;
You can’t perform that action at this time.
0 commit comments