File: threadsafe_function_unref.cc

package info (click to toggle)
node-addon-api 8.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,248 kB
  • sloc: cpp: 15,431; javascript: 5,631; ansic: 157; makefile: 7
file content (55 lines) | stat: -rw-r--r-- 1,312 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "napi.h"
#include "test_helper.h"

#if (NAPI_VERSION > 3)

using namespace Napi;

namespace {

static Value TestUnref(const CallbackInfo& info) {
  Napi::Env env = info.Env();
  Object global = env.Global();
  Object resource = info[0].As<Object>();
  Function cb = info[1].As<Function>();
  Function setTimeout = MaybeUnwrap(global.Get("setTimeout")).As<Function>();
  ThreadSafeFunction* tsfn = new ThreadSafeFunction;

  *tsfn = ThreadSafeFunction::New(
      info.Env(), cb, resource, "Test", 1, 1, [tsfn](Napi::Env /* env */) {
        delete tsfn;
      });

  tsfn->BlockingCall();

  setTimeout.Call(
      global,
      {Function::New(
           env, [tsfn](const CallbackInfo& info) { tsfn->Unref(info.Env()); }),
       Number::New(env, 100)});

  return info.Env().Undefined();
}

static Value TestRef(const CallbackInfo& info) {
  Function cb = info[1].As<Function>();

  auto tsfn = ThreadSafeFunction::New(info.Env(), cb, "testRes", 1, 1);

  tsfn.BlockingCall();
  tsfn.Unref(info.Env());
  tsfn.Ref(info.Env());

  return info.Env().Undefined();
}

}  // namespace

Object InitThreadSafeFunctionUnref(Env env) {
  Object exports = Object::New(env);
  exports["testUnref"] = Function::New(env, TestUnref);
  exports["testRef"] = Function::New(env, TestRef);
  return exports;
}

#endif