-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.cc
93 lines (73 loc) · 2.71 KB
/
module.cc
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <future>
#include <iostream>
#include <thread>
#include <chrono>
#include "napi_experimental.h"
#include "synchronizer/synchronizer.h"
#include "threadsafe-node-calls/ThreadsafeNodeCalls.h"
using namespace std::chrono_literals;
std::thread::id main_thread;
std::string GetThreadName() {
if (std::this_thread::get_id() == main_thread) {
return "MainThread ";
}
return "WorkerThread";
}
void SumAsync(const Napi::CallbackInfo& info) {
// switch to C-NAPI, because we need to copy a reference inside a lambda,
// which is not working with Napi::Reference<..> at the moment
napi_ref js_cb_ref;
CHECK_NAPI(napi_create_reference(info.Env(), info[0], 1, &js_cb_ref));
Synchronized<int>(info.Env(),
// called from node thread; can call `cb(...)` from any thread
[](auto&& cb) {
std::cout << GetThreadName() << ": SumAsync -> async_fn" << std::endl;
std::thread([cb=std::move(cb)]() {
std::cout << GetThreadName() << ": SumAsync -> async_fn -> std::thread" << std::endl;
std::this_thread::sleep_for(5s);
int sum = 0;
for (int i = 0; i < 100000; i++) {
sum += i;
}
cb(std::move(sum));
}).detach();
}, [js_cb_ref](Napi::Env env, int result) {
std::cout << GetThreadName() << ": SumAsync -> sync_fn" << std::endl;
auto&& cb = Napi::FunctionReference(env, js_cb_ref);
cb.Call({
Napi::Number::New(env, result)
});
});
}
void SumAsync2(const Napi::CallbackInfo& info) {
// switch to C-NAPI, because we need to copy a reference inside a lambda,
// which is not working with Napi::Reference<..> at the moment
napi_ref cb_ref;
CHECK_NAPI(napi_create_reference(info.Env(), info[0], 1, &cb_ref));
auto&& node_calls = ThreadsafeNodeCalls::Create(info.Env());
std::cout << GetThreadName() << ": SumAsync2" << std::endl;
// async
std::thread([node_calls, cb_ref]() {
std::cout << GetThreadName() << ": SumAsync2 -> std::thread" << std::endl;
std::this_thread::sleep_for(5s);
int sum = 0;
for (int i = 0; i < 100000; i++) {
sum += i;
}
// we can call this from any thread
node_calls->RunInNodeThread([cb_ref, sum](Napi::Env env) {
std::cout << GetThreadName() << ": SumAsync2 -> std::thread -> RunInNodeThread" << std::endl;
auto&& cb = Napi::FunctionReference(env, cb_ref);
cb.Call({
Napi::Number::New(env, sum)
});
});
}).detach();
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
main_thread = std::this_thread::get_id();
exports["sumAsync"] = Napi::Function::New(env, SumAsync, nullptr);
exports["sumAsync2"] = Napi::Function::New(env, SumAsync2, nullptr);
return exports;
}
NODE_API_MODULE(napi_experimental, Init)