0

The title may be a little confusing. What I wanna do is that I have a shared value, which need to be shared as part of node native addon. The addon itself is context aware, which means it may be loaded from many worker threads. So my question is how should make the write & read operation to the shared value to be thread-safe. Here I provide a minimal project to demonstrate this.

#include <node.h>
#include "nan.h"

// shared value
double value = 0;

NAN_METHOD(SetValue)
{
  if (!info[0]->IsNumber())
  {
    return Nan::ThrowTypeError("Number expected");
  }

  value = info[0].As<v8::Number>()->Value();
}

NAN_METHOD(GetValue)
{
  info.GetReturnValue().Set(Nan::New<v8::Number>(value));
}

NAN_MODULE_INIT(Init)
{
  // set_v & get_v may be called from many worker threads
  Nan::Set(target, Nan::New<v8::String>("set_v").ToLocalChecked(), Nan::New<v8::Function>(SetValue));
  Nan::Set(target, Nan::New<v8::String>("get_v").ToLocalChecked(), Nan::New<v8::Function>(GetValue));
}

NODE_MODULE_INIT()
{
  Init(exports);
}
branson
  • 55
  • 4
  • The easy (but possibly overkill) way would be: `std::atomic value;` – Jerry Coffin Feb 10 '22 at 16:09
  • @JerryCoffin Thanks for your comment!. But in context of node addon, I think there should be a libuv specific way to do this. I just quiet don't understand how when it comes with v8 and nodejs worker thread – branson Feb 11 '22 at 02:13
  • I found an acceptable solution, which i commented on this issue https://github.com/nodejs/help/issues/3735. – branson Feb 13 '22 at 03:08

0 Answers0