gpt4 book ai didi

c++ - 为什么 "Isolate::GerCurrent()"在异步线程中为Null?

转载 作者:行者123 更新时间:2023-11-30 05:35:17 29 4
gpt4 key购买 nike

我的最终目标是解决这个problem ,但我陷入了一些非常基本的东西。

我的整个C++ Module基本如下:

void AsyncWork(void *arg) {
Isolate* isolate = Isolate::GetCurrent(); // isolate is NULL
if (isolate != NULL) {
HandleScope scope(isolate);
}
else {
printf("isolate is null\n");
return;
}
// ...
}


void testAsync(const FunctionCallbackInfo<Value>& args) {
uv_thread_t id;
int data = 10;
uv_thread_create(&id, AsyncWork, &data);
}

void init(Handle<Object> target) {
NODE_SET_METHOD(target, "testAsync", testAsync);
}

NODE_MODULE(MyCppModule, init);

为什么在 AsyncWork 中调用 Isolate::GetCurrent()isolate 为 NULL?

最佳答案

好吧,好像我设置错了,不应该在工作线程中调用 Isolate::GetCurrent()。而是在主线程上注册一个回调。

static uv_async_t async;
static int i;

void AsyncWork(void *arg) {
for (i = 0; i < 5; ++i) {
async.data = (void*)&i;
uv_async_send(&async);
Sleep(1000);
}
}

void testCallback(uv_async_t *handle) {
Isolate* isolate = Isolate::GetCurrent();
if (isolate != NULL) {
HandleScope scope(isolate);
printf("Yay\n");
}
else {
printf("isolate is null\n");
}
int data = *((int*)handle->data);
printf("data: %d\n", data);
}

void testAsync(const FunctionCallbackInfo<Value>& args) {
uv_thread_t id;
int data = 10;
uv_async_init(uv_default_loop(), &async, testCallback);
uv_thread_create(&id, AsyncWork, &data);
}

void init(Handle<Object> target) {
NODE_SET_METHOD(target, "testAsync", testAsync);
}

NODE_MODULE(MyCppModule, init);

关于c++ - 为什么 "Isolate::GerCurrent()"在异步线程中为Null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33940750/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com