正确处理Persistent <arraybuffer>

时间:2016-03-28 14:20:17

标签: c++ v8 arraybuffer

我的代码非常简单:

struct Dyn {
 float *ptr;
 int n;
};


void setWeakFunction1(const WeakCallbackInfo<Dyn> &data) {
}
void setWeakFunction(const WeakCallbackInfo<Dyn> &data) {
 auto *v = data.GetParameter();
 data.SetSecondPassCallback(setWeakFunction1);
 std::cout << v->n << " Collector\n";
 delete[] v->ptr;
 delete v;

}

void getIndex(const FunctionCallbackInfo<Value> &args) {
  Dyn *d = new Dyn;
  float *ptr = new float[amount];
  for (size_t i = 0; i < amount; ++i) {
    ptr[i] = i + 2;
  }

  auto isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  Local<ArrayBuffer> ab =
      ArrayBuffer::New(isolate, ptr, amount * sizeof(float));
  Persistent<ArrayBuffer> pab(isolate, ab);
  pab.SetWeak(d, setWeakFunction, WeakCallbackType::kInternalFields);
  pab.MarkIndependent();
  args.GetReturnValue().Set(ab);
}

void RegisterModule(Local<Object> exports, Local<Object>) {
 auto isolate = Isolate::GetCurrent();
 exports->Set(String::NewFromUtf8(isolate, "getIndex"),
           FunctionTemplate::New(isolate, getIndex)->GetFunction());
}

NODE_MODULE(commander, RegisterModule)

这段代码对我来说有些尴尬。

由于有一个计数器,我希望,为我创建的每个setWeakFunction存储调用Persistence。当浮点数小于10000时,它会调用每个持久单元格。但是当浮动的大小变为100 000时,它不会尝试处理任何对象,直到有1Gb的内存被吃掉,然后它会不断移除,但会留下2-3个对象。

我有一个想法,垃圾收集器为一堆对象调用WeakCallback一次,但没有找到信息,确认了这一点。

更糟糕的是,我从未见过任何垃圾收集调用1000 000浮点数组。

如何正确处理此数组?

1 个答案:

答案 0 :(得分:0)

让我尝试修复上面的代码:

struct Dyn {
    Persistent<ArrayBuffer> pab;
    float *ptr;
    int n;
};

void setWeakFunction(const WeakCallbackInfo<Dyn> &data) {
    auto *v = data.GetParameter();
    std::cout << v->n << " Collector\n";
    v->pab.Reset();
    delete[] v->ptr;
    delete v;

}

void getIndex(const FunctionCallbackInfo<Value> &args) {
    Dyn *d = new Dyn;
    float *ptr = new float[amount];
    for (size_t i = 0; i < amount; ++i) {
        ptr[i] = i + 2;
    }

    auto isolate = args.GetIsolate();
    HandleScope scope(isolate);
    Local<ArrayBuffer> ab =
        ArrayBuffer::New(isolate, ptr, amount * sizeof(float), ArrayBufferCreationMode::kExternalized);
    d->pab.Reset(isolate, ab);
    d->pab.SetWeak(d, setWeakFunction, WeakCallbackType::kParameter);
    d->pab.MarkIndependent();
    args.GetReturnValue().Set(ab);
}

void RegisterModule(Local<Object> exports, Local<Object>) {
    auto isolate = Isolate::GetCurrent();
    exports->Set(String::NewFromUtf8(isolate, "getIndex"),
        FunctionTemplate::New(isolate, getIndex)->GetFunction());
}

NODE_MODULE(commander, RegisterModule)