Nodejs worker threads shared object/store

后端 未结 1 1811
醉话见心
醉话见心 2021-02-07 09:01

So, I was reading some stuff regarding nodejs and I was amazed when I came across Worker Threads.

Having threads in my opinion is a great plus especially if you combine

1条回答
  •  失恋的感觉
    2021-02-07 09:21

    ECMA Script contains no shared objects but it have SharedArrayBuffer. And you can implement such behavior on your own writing data directly in buffer using DataView and wrapper:

    // Shared value
    class SharedPoint {
      constructor(array) {
        this.dataview = new DataView(array);
      }
    
      set x(value) {
        this.dataview.setUint8(0, value);
      }
    
      set y(value) {
        this.dataview.setUint8(1, value);
      }
    
      get x() {
        return this.dataview.getUint8(0);
      }
    
      get y() {
        return this.dataview.getUint8(1);
      }
    }
    
    // Usage
    
    const buffer = new SharedArrayBuffer(2);
    
    // Create two instances of shared point.
    const point0 = new SharedPoint(buffer);
    const point1 = new SharedPoint(buffer);
    
    // Get initial values for point #1
    console.log('x', point1.x); // 0
    console.log('y', point1.y); // 0
    
    // Update point #0
    point0.x = 64;
    point0.y = 32;
    
    // Get changes in point #1
    console.log('x', point1.x); // 64
    console.log('y', point1.y); // 32
    

    You are able to create class which can manipulate strings or C-like structures. While SharedArrayBuffer is tranferable object it can be shared between worker and main process.

    ⚠️ Note Due to Spectre attack SharedArrayBuffer was disabled by all major browsers and reenabled in Chrome since version 68 and in Firefox since version 79. Check browsers support on can i use.

    0 讨论(0)
提交回复
热议问题