-
Notifications
You must be signed in to change notification settings - Fork 594
/
example.cc
163 lines (133 loc) · 4.47 KB
/
example.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#include <napi.h>
#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <thread>
using namespace Napi;
class ThreadSafeAsyncIteratorExample
: public ObjectWrap<ThreadSafeAsyncIteratorExample> {
public:
ThreadSafeAsyncIteratorExample(const CallbackInfo& info)
: ObjectWrap<ThreadSafeAsyncIteratorExample>(info),
_current(info[0].As<Number>()),
_last(info[1].As<Number>()) {}
static Object Init(Napi::Env env, Napi::Object exports);
Napi::Value Iterator(const CallbackInfo& info);
private:
using Context = ThreadSafeAsyncIteratorExample;
struct DataType {
std::unique_ptr<Promise::Deferred> deferred;
bool done;
std::optional<int> value;
};
static void CallJs(Napi::Env env,
Function callback,
Context* context,
DataType* data);
using TSFN = TypedThreadSafeFunction<Context, DataType, CallJs>;
using FinalizerDataType = void;
int _current;
int _last;
TSFN _tsfn;
std::thread _thread;
std::unique_ptr<Promise::Deferred> _deferred;
// Thread-safety
std::mutex _mtx;
std::condition_variable _cv;
void threadEntry();
static void FinalizerCallback(Napi::Env env,
void*,
ThreadSafeAsyncIteratorExample* context);
};
Object ThreadSafeAsyncIteratorExample::Init(Napi::Env env,
Napi::Object exports) {
Napi::Function func =
DefineClass(env,
"ThreadSafeAsyncIteratorExample",
{InstanceMethod(Napi::Symbol::WellKnown(env, "asyncIterator"),
&ThreadSafeAsyncIteratorExample::Iterator)});
exports.Set("ThreadSafeAsyncIteratorExample", func);
return exports;
}
Napi::Value ThreadSafeAsyncIteratorExample::Iterator(const CallbackInfo& info) {
auto env = info.Env();
if (_thread.joinable()) {
Napi::Error::New(env, "Concurrent iterations not implemented.")
.ThrowAsJavaScriptException();
return Napi::Value();
}
_tsfn =
TSFN::New(info.Env(),
"tsfn",
0,
1,
this,
std::function<decltype(FinalizerCallback)>(FinalizerCallback));
// To prevent premature garbage collection; Unref in TFSN finalizer
Ref();
// Create thread
_thread = std::thread(&ThreadSafeAsyncIteratorExample::threadEntry, this);
// Create iterable
auto iterable = Napi::Object::New(env);
iterable["next"] =
Function::New(env, [this](const CallbackInfo& info) -> Napi::Value {
std::lock_guard<std::mutex> lk(_mtx);
auto env = info.Env();
if (_deferred) {
Napi::Error::New(env, "Concurrent iterations not implemented.")
.ThrowAsJavaScriptException();
return Napi::Value();
}
_deferred = std::make_unique<Promise::Deferred>(env);
_cv.notify_all();
return _deferred->Promise();
});
return iterable;
}
void ThreadSafeAsyncIteratorExample::threadEntry() {
while (true) {
std::unique_lock<std::mutex> lk(_mtx);
_cv.wait(lk, [this] { return this->_deferred != nullptr; });
auto done = _current > _last;
if (done) {
_tsfn.BlockingCall(new DataType{std::move(this->_deferred), true, {}});
break;
} else {
std::this_thread::sleep_for(
std::chrono::seconds(1)); // Simulate CPU-intensive work
_tsfn.BlockingCall(
new DataType{std::move(this->_deferred), false, _current++});
}
}
_tsfn.Release();
}
void ThreadSafeAsyncIteratorExample::CallJs(Napi::Env env,
Function callback,
Context* context,
DataType* data) {
if (env != nullptr) {
auto value = Object::New(env);
if (data->done) {
value["done"] = Boolean::New(env, true);
} else {
value["done"] = Boolean::New(env, false);
value["value"] = Number::New(env, data->value.value());
}
data->deferred->Resolve(value);
}
if (data != nullptr) {
delete data;
}
}
void ThreadSafeAsyncIteratorExample::FinalizerCallback(
Napi::Env env, void*, ThreadSafeAsyncIteratorExample* context) {
context->_thread.join();
context->Unref();
}
Napi::Object Init(Napi::Env env, Object exports) {
ThreadSafeAsyncIteratorExample::Init(env, exports);
return exports;
}
NODE_API_MODULE(example, Init)