env->thread_id() matches main thread id even when node addon is loaded on worker thread
Details
I have been trying to read is_main_thread and thread_id from environment when my native addon is loaded on the main thread and worker threads and noticed that it is always the same.
First of all, my experience here is quite limited and this may be expected behavior so I apologize if this is a silly question. I am aware that both isMainThread and threadId are exported already from node:worker_thread, but my addon generates the majority of the data inside c++ (isMainThread and threadId are just a small subset and just serve as an example here) and I would like to keep most of that logic centralized in c. I have tried following the context aware addon documentation and looked at the worker source code, but I was unsuccessful in reading the correct threadId or isMainThread based on where my addon is being called from.
Node.js version
16.6
Example code
#define NODE_WANT_INTERNALS 1
#include <env.h>
#include <env-inl.h>
#include <nan.h>
#include <v8-profiler.h>
using namespace v8;
class ExternalCarrier {
public:
boolean_t is_main_thread;
uint64_t thread_id;
};
static void ExportedFn(const v8::FunctionCallbackInfo<v8::Value>& args) {
ExternalCarrier* carrier = reinterpret_cast<ExternalCarrier*>(args.Data().As<External>()->Value());
Local<Object> returned = Nan::New<Object>();
Nan::Set(returned, Nan::New<String>("isMainThread").ToLocalChecked(),
Nan::New<Boolean>(carrier->is_main_thread));
Nan::Set(returned, Nan::New<String>("threadId").ToLocalChecked(),
Nan::New<Number>(carrier->thread_id));
args.GetReturnValue().Set(returned);
}
NODE_MODULE_INIT(/* exports, module, context */){
node::Environment* env = (node::GetCurrentEnvironment(context));
ExternalCarrier* carrier = new ExternalCarrier();
carrier->thread_id = env->thread_id();
carrier->is_main_thread = env->is_main_thread();
Local<External> external = External::New(env->isolate(), carrier);
exports->Set(context,
Nan::New<String>("exportedFn").ToLocalChecked(),
FunctionTemplate::New(env->isolate(), ExportedFn, external)->GetFunction(context).ToLocalChecked()).FromJust();
};
I do know that isMainThread and threadId are exported from node:worker_threads, but I would ideally like to keep this logic inside the addon. Above is a small part of the code that reproduces the issue.
Operating system
macOS 12.5.1 (Darwin Kernel Version 21.6.0, arm64, m1 pro)
Scope
native addon, workers, env
Module and version
Not applicable