(ES6) ES6 (2016)

RaceConditions (RC01)

   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 sharedArray = new Int32Array(sharedBuffer);
   6:  sharedArray[0] = 0; // Initialize the shared value to 0
   7:  
   8:  // Start the workers
   9:  const worker1 = new Worker('./RC#02.js');
  10:  const worker2 = new Worker('./RC#02.js');
  11:  
  12:  // Send the SharedArrayBuffer to both workers
  13:  worker1.postMessage(sharedBuffer);
  14:  worker2.postMessage(sharedBuffer);
  15:  
  16:  // Listen for messages from the workers
  17:  worker1.on('message', (message) => {
  18:      console.log(message);
  19:  });
  20:  
  21:  worker2.on('message', (message) => {
  22:      console.log(message);
  23:  });
  24:  
  25:  // Wait for both workers to finish
  26:  Promise.all([
  27:      new Promise((resolve) => worker1.on('message', resolve)),
  28:      new Promise((resolve) => worker2.on('message', resolve)),
  29:  ]).then(() => {
  30:      console.log("Final shared value:", sharedArray[0]); // Should be 200000
  31:  });



Race condition  - Main thread

Worker 1 done
Worker 1 done
Final shared value: 117352





RaceConditions context:






ES6 context:



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