File: binding.cc

package info (click to toggle)
nodejs 22.14.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 246,928 kB
  • sloc: cpp: 1,582,349; javascript: 582,017; ansic: 82,400; python: 60,561; sh: 4,009; makefile: 2,263; asm: 1,732; pascal: 1,565; perl: 248; lisp: 222; xml: 42
file content (72 lines) | stat: -rw-r--r-- 2,184 bytes parent folder | download | duplicates (6)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <node.h>
#include <v8.h>
#include <thread>  // NOLINT(build/c++11)

using node::Environment;
using v8::Context;
using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Maybe;
using v8::Object;
using v8::String;
using v8::Value;

static std::thread interrupt_thread;

void ScheduleInterrupt(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  HandleScope handle_scope(isolate);
  Environment* env = node::GetCurrentEnvironment(isolate->GetCurrentContext());

  interrupt_thread = std::thread([=]() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    node::RequestInterrupt(
        env,
        [](void* data) {
          // Interrupt is called from JS thread.
          interrupt_thread.join();
          exit(0);
        },
        nullptr);
  });
}

void ScheduleInterruptWithJS(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  HandleScope handle_scope(isolate);
  Environment* env = node::GetCurrentEnvironment(isolate->GetCurrentContext());

  interrupt_thread = std::thread([=]() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    node::RequestInterrupt(
        env,
        [](void* data) {
          // Interrupt is called from JS thread.
          interrupt_thread.join();
          Isolate* isolate = static_cast<Isolate*>(data);
          HandleScope handle_scope(isolate);
          Local<Context> ctx = isolate->GetCurrentContext();
          Local<String> str =
              String::NewFromUtf8(isolate, "interrupt").ToLocalChecked();
          // Calling into JS should abort immediately.
          Maybe<bool> result = ctx->Global()->Set(ctx, str, str);
          // Should not reach here.
          if (!result.IsNothing()) {
            // Called into JavaScript.
            exit(2);
          }
          // Maybe exception thrown.
          exit(1);
        },
        isolate);
  });
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "scheduleInterrupt", ScheduleInterrupt);
  NODE_SET_METHOD(exports, "ScheduleInterruptWithJS", ScheduleInterruptWithJS);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, init)