(ES6) ES6 (2016)

SharedBuffer (SB01)

   1:  import { Worker } from 'worker_threads';
   2:  
   3:  // Create a SharedArrayBuffer and a view into it
   4:  const sharedBuffer = new SharedArrayBuffer(4); // 4 bytes for a 32-bit integer
   5:  const counter = new Int32Array(sharedBuffer);
   6:  counter[0] = 0; // Initialize the counter to 0
   7:  
   8:  // Start the worker
   9:  const worker = new Worker('./SB#02.js');
  10:  worker.postMessage(sharedBuffer); // Send the SharedArrayBuffer to the worker
  11:  
  12:  // Listen for messages from the worker
  13:  worker.on('message', (message) => {
  14:      console.log("Message from worker:", message);
  15:      console.log("Final counter value in main thread:", counter[0]); // Output: 100000
  16:  });



Counter (Thread-Safe Increment) Main Thread

Message from worker: Counter incremented.
Final counter value in main thread: 100000





SharedBuffer context:






ES6 context:



Comments ( )
Link to this page: http://www.vb-net.com/JavascriptES6/SB01.htm
< THANKS ME>