-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreadSafeFunction.mm
More file actions
817 lines (689 loc) · 22 KB
/
ThreadSafeFunction.mm
File metadata and controls
817 lines (689 loc) · 22 KB
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
#include <CoreFoundation/CFRunLoop.h>
#include <algorithm>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include "js_native_api.h"
#include "js_native_tsfn.h"
#include "jsr.h"
#include "runtime/Runtime.h"
#ifdef TARGET_ENGINE_V8
#include "v8-api.h"
#endif
typedef struct napi_async_context__* napi_async_context;
typedef struct napi_callback_scope__* napi_callback_scope;
typedef napi_env node_api_basic_env;
typedef struct {
uint32_t major;
uint32_t minor;
uint32_t patch;
const char* release;
} napi_node_version;
typedef void(NAPI_CDECL* napi_cleanup_hook)(void* arg);
typedef struct napi_async_cleanup_hook_handle__* napi_async_cleanup_hook_handle;
typedef void(NAPI_CDECL* napi_async_cleanup_hook)(
napi_async_cleanup_hook_handle handle, void* data);
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_make_callback(napi_env env, napi_async_context async_context,
napi_value recv, napi_value func, size_t argc,
const napi_value* argv, napi_value* result);
struct napi_async_context__ {
napi_env env = nullptr;
napi_ref resource_ref = nullptr;
napi_ref resource_name_ref = nullptr;
};
struct napi_callback_scope__ {
napi_env env = nullptr;
napi_async_context async_context = nullptr;
bool closed = false;
};
struct napi_async_cleanup_hook_handle__ {
node_api_basic_env env = nullptr;
napi_async_cleanup_hook hook = nullptr;
void* data = nullptr;
bool removed = false;
};
struct napi_threadsafe_function__ {
napi_env env = nullptr;
napi_ref callback_ref = nullptr;
napi_threadsafe_function_call_js call_js_cb = nullptr;
void* context = nullptr;
void* thread_finalize_data = nullptr;
napi_finalize thread_finalize_cb = nullptr;
CFRunLoopRef run_loop = nullptr;
std::mutex mutex;
std::condition_variable queue_cv;
size_t max_queue_size = 0;
size_t queued_calls = 0;
size_t thread_count = 0;
bool closing = false;
bool finalize_scheduled = false;
};
struct TSFNCall {
napi_threadsafe_function__* tsfn = nullptr;
void* data = nullptr;
bool blocking = false;
std::mutex done_mutex;
std::condition_variable done_cv;
bool done = false;
};
struct EnvCleanupState {
std::vector<std::pair<napi_cleanup_hook, void*>> env_hooks;
std::vector<napi_async_cleanup_hook_handle__*> async_hooks;
std::vector<napi_async_cleanup_hook_handle__*> deferred_delete_async_hooks;
bool draining_async_hooks = false;
};
static std::mutex g_cleanup_hooks_mutex;
static std::condition_variable g_cleanup_hooks_cv;
static std::unordered_map<node_api_basic_env, EnvCleanupState>
g_cleanup_hooks;
static bool IsCleanupStateEmpty(const EnvCleanupState& state) {
return state.env_hooks.empty() && state.async_hooks.empty() &&
state.deferred_delete_async_hooks.empty() && !state.draining_async_hooks;
}
static void EraseCleanupStateIfUnused(node_api_basic_env env) {
auto it = g_cleanup_hooks.find(env);
if (it != g_cleanup_hooks.end() && IsCleanupStateEmpty(it->second)) {
g_cleanup_hooks.erase(it);
}
}
static size_t ResolveLength(const char* value, size_t value_len) {
if (value == nullptr) {
return 0;
}
if (value_len == NAPI_AUTO_LENGTH) {
return std::strlen(value);
}
return value_len;
}
static CFRunLoopRef GetRuntimeRunLoop(napi_env env) {
auto runtime = nativescript::Runtime::GetRuntime(env);
if (runtime != nullptr && runtime->RuntimeLoop() != nullptr) {
return runtime->RuntimeLoop();
}
return CFRunLoopGetMain();
}
static bool ScheduleOnRunLoop(
CFRunLoopRef runLoop, std::shared_ptr<std::function<void()>> task) {
if (runLoop == nullptr) {
return false;
}
if (CFRunLoopGetCurrent() == runLoop) {
(*task)();
return true;
}
CFRunLoopPerformBlock(runLoop, kCFRunLoopCommonModes, ^{
(*task)();
});
CFRunLoopWakeUp(runLoop);
return true;
}
static inline void IncrementCallbackScopes(napi_env env) {
#ifdef TARGET_ENGINE_V8
env->open_callback_scopes++;
#else
(void)env;
#endif
}
static inline napi_status DecrementCallbackScopes(napi_env env) {
#ifdef TARGET_ENGINE_V8
if (env->open_callback_scopes <= 0) {
return napi_callback_scope_mismatch;
}
env->open_callback_scopes--;
#else
(void)env;
#endif
return napi_ok;
}
static void ScheduleFinalizeIfNeeded(napi_threadsafe_function__* tsfn);
static void FinalizeTSFN(napi_threadsafe_function__* tsfn) {
NapiScope scope(tsfn->env);
if (tsfn->thread_finalize_cb != nullptr) {
tsfn->thread_finalize_cb(tsfn->env, tsfn->thread_finalize_data, nullptr);
}
if (tsfn->callback_ref != nullptr) {
napi_delete_reference(tsfn->env, tsfn->callback_ref);
tsfn->callback_ref = nullptr;
}
if (tsfn->run_loop != nullptr) {
CFRelease(tsfn->run_loop);
tsfn->run_loop = nullptr;
}
delete tsfn;
}
static void ScheduleFinalizeIfNeeded(napi_threadsafe_function__* tsfn) {
bool shouldFinalize = false;
{
std::lock_guard<std::mutex> lock(tsfn->mutex);
shouldFinalize = tsfn->closing && tsfn->thread_count == 0 &&
tsfn->queued_calls == 0 && !tsfn->finalize_scheduled;
if (shouldFinalize) {
tsfn->finalize_scheduled = true;
}
}
if (!shouldFinalize) {
return;
}
auto task = std::make_shared<std::function<void()>>(
[tsfn]() { FinalizeTSFN(tsfn); });
if (!ScheduleOnRunLoop(tsfn->run_loop, task)) {
// If scheduling is impossible (loop already gone), finalize eagerly.
(*task)();
}
}
static void ExecuteTSFNCall(const std::shared_ptr<TSFNCall>& call) {
auto* tsfn = call->tsfn;
{
NapiScope scope(tsfn->env);
napi_value jsCallback = nullptr;
if (tsfn->callback_ref != nullptr) {
napi_get_reference_value(tsfn->env, tsfn->callback_ref, &jsCallback);
}
if (tsfn->call_js_cb != nullptr) {
tsfn->call_js_cb(tsfn->env, jsCallback, tsfn->context, call->data);
} else if (jsCallback != nullptr) {
napi_value recv = nullptr;
napi_get_undefined(tsfn->env, &recv);
napi_make_callback(tsfn->env, nullptr, recv, jsCallback, 0, nullptr,
nullptr);
}
}
{
std::lock_guard<std::mutex> lock(tsfn->mutex);
if (tsfn->queued_calls > 0) {
tsfn->queued_calls--;
}
}
tsfn->queue_cv.notify_all();
if (call->blocking) {
{
std::lock_guard<std::mutex> lock(call->done_mutex);
call->done = true;
}
call->done_cv.notify_one();
}
ScheduleFinalizeIfNeeded(tsfn);
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_async_init(napi_env env, napi_value async_resource,
napi_value async_resource_name, napi_async_context* result) {
if (env == nullptr || result == nullptr) {
return napi_invalid_arg;
}
auto* context = new napi_async_context__();
context->env = env;
if (async_resource != nullptr) {
napi_status status =
napi_create_reference(env, async_resource, 1, &context->resource_ref);
if (status != napi_ok) {
delete context;
return status;
}
}
if (async_resource_name != nullptr) {
napi_status status = napi_create_reference(env, async_resource_name, 1,
&context->resource_name_ref);
if (status != napi_ok) {
if (context->resource_ref != nullptr) {
napi_delete_reference(env, context->resource_ref);
}
delete context;
return status;
}
}
*result = context;
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_async_destroy(napi_env env, napi_async_context async_context) {
if (env == nullptr || async_context == nullptr) {
return napi_invalid_arg;
}
if (async_context->env != env) {
return napi_invalid_arg;
}
if (async_context->resource_ref != nullptr) {
napi_delete_reference(env, async_context->resource_ref);
async_context->resource_ref = nullptr;
}
if (async_context->resource_name_ref != nullptr) {
napi_delete_reference(env, async_context->resource_name_ref);
async_context->resource_name_ref = nullptr;
}
delete async_context;
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_open_callback_scope(napi_env env, napi_value resource_object,
napi_async_context context,
napi_callback_scope* result) {
if (env == nullptr || resource_object == nullptr || context == nullptr ||
result == nullptr) {
return napi_invalid_arg;
}
auto* scope = new napi_callback_scope__();
scope->env = env;
scope->async_context = context;
IncrementCallbackScopes(env);
*result = scope;
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_close_callback_scope(napi_env env, napi_callback_scope scope) {
if (env == nullptr || scope == nullptr) {
return napi_invalid_arg;
}
if (scope->env != env || scope->closed) {
return napi_callback_scope_mismatch;
}
napi_status status = DecrementCallbackScopes(env);
scope->closed = true;
delete scope;
return status;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_make_callback(napi_env env, napi_async_context async_context,
napi_value recv, napi_value func, size_t argc,
const napi_value* argv, napi_value* result) {
if (env == nullptr || recv == nullptr || func == nullptr) {
return napi_invalid_arg;
}
if (argc > 0 && argv == nullptr) {
return napi_invalid_arg;
}
auto invoke = std::make_shared<std::function<napi_status()>>([=]() {
NapiScope scope(env);
napi_callback_scope callbackScope = nullptr;
if (async_context != nullptr) {
napi_value resourceObject = recv;
if (async_context->resource_ref != nullptr) {
napi_get_reference_value(env, async_context->resource_ref,
&resourceObject);
}
napi_status openStatus =
napi_open_callback_scope(env, resourceObject, async_context,
&callbackScope);
if (openStatus != napi_ok) {
return openStatus;
}
}
napi_status callStatus =
napi_call_function(env, recv, func, argc, argv, result);
if (callbackScope != nullptr) {
napi_status closeStatus = napi_close_callback_scope(env, callbackScope);
if (callStatus == napi_ok) {
callStatus = closeStatus;
}
}
return callStatus;
});
CFRunLoopRef runLoop = GetRuntimeRunLoop(env);
if (runLoop != nullptr && CFRunLoopGetCurrent() != runLoop) {
std::mutex mutex;
std::condition_variable cv;
bool done = false;
napi_status status = napi_generic_failure;
auto task = std::make_shared<std::function<void()>>([&]() {
status = (*invoke)();
{
std::lock_guard<std::mutex> lock(mutex);
done = true;
}
cv.notify_one();
});
if (!ScheduleOnRunLoop(runLoop, task)) {
return napi_generic_failure;
}
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [&]() { return done; });
return status;
}
return (*invoke)();
}
extern "C" NAPI_EXTERN void NAPI_CDECL
napi_fatal_error(const char* location, size_t location_len,
const char* message, size_t message_len) {
const size_t resolved_location_len = ResolveLength(location, location_len);
const size_t resolved_message_len = ResolveLength(message, message_len);
std::string location_str =
location == nullptr ? std::string() : std::string(location, resolved_location_len);
std::string message_str =
message == nullptr ? std::string() : std::string(message, resolved_message_len);
if (!location_str.empty()) {
std::fprintf(stderr, "FATAL ERROR: %s: %s\n", location_str.c_str(),
message_str.c_str());
} else {
std::fprintf(stderr, "FATAL ERROR: %s\n", message_str.c_str());
}
std::fflush(stderr);
std::abort();
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_fatal_exception(napi_env env, napi_value err) {
if (env == nullptr || err == nullptr) {
return napi_invalid_arg;
}
return napi_throw(env, err);
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_get_node_version(node_api_basic_env env, const napi_node_version** version) {
(void)env;
if (version == nullptr) {
return napi_invalid_arg;
}
static const napi_node_version kVersion = {
0,
0,
0,
"nativescript",
};
*version = &kVersion;
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_add_env_cleanup_hook(node_api_basic_env env, napi_cleanup_hook fun,
void* arg) {
if (env == nullptr || fun == nullptr) {
return napi_invalid_arg;
}
std::lock_guard<std::mutex> lock(g_cleanup_hooks_mutex);
auto& state = g_cleanup_hooks[env];
state.env_hooks.emplace_back(fun, arg);
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_remove_env_cleanup_hook(node_api_basic_env env, napi_cleanup_hook fun,
void* arg) {
if (env == nullptr || fun == nullptr) {
return napi_invalid_arg;
}
std::lock_guard<std::mutex> lock(g_cleanup_hooks_mutex);
auto it = g_cleanup_hooks.find(env);
if (it == g_cleanup_hooks.end()) {
return napi_invalid_arg;
}
auto& hooks = it->second.env_hooks;
for (auto hook_it = hooks.rbegin(); hook_it != hooks.rend(); ++hook_it) {
if (hook_it->first == fun && hook_it->second == arg) {
hooks.erase(std::next(hook_it).base());
EraseCleanupStateIfUnused(env);
return napi_ok;
}
}
return napi_invalid_arg;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_add_async_cleanup_hook(node_api_basic_env env, napi_async_cleanup_hook hook,
void* arg,
napi_async_cleanup_hook_handle* remove_handle) {
if (env == nullptr || hook == nullptr) {
return napi_invalid_arg;
}
auto* handle = new napi_async_cleanup_hook_handle__();
handle->env = env;
handle->hook = hook;
handle->data = arg;
std::lock_guard<std::mutex> lock(g_cleanup_hooks_mutex);
auto& state = g_cleanup_hooks[env];
state.async_hooks.push_back(handle);
if (remove_handle != nullptr) {
*remove_handle = handle;
}
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_remove_async_cleanup_hook(napi_async_cleanup_hook_handle remove_handle) {
if (remove_handle == nullptr) {
return napi_invalid_arg;
}
auto* handle = static_cast<napi_async_cleanup_hook_handle__*>(remove_handle);
node_api_basic_env env = handle->env;
std::lock_guard<std::mutex> lock(g_cleanup_hooks_mutex);
auto it = g_cleanup_hooks.find(env);
if (it == g_cleanup_hooks.end() || handle->removed) {
return napi_invalid_arg;
}
auto& state = it->second;
auto vec_it =
std::find(state.async_hooks.begin(), state.async_hooks.end(), handle);
if (vec_it == state.async_hooks.end()) {
return napi_invalid_arg;
}
handle->removed = true;
state.async_hooks.erase(vec_it);
if (state.draining_async_hooks) {
state.deferred_delete_async_hooks.push_back(handle);
if (state.async_hooks.empty()) {
g_cleanup_hooks_cv.notify_all();
}
} else {
delete handle;
EraseCleanupStateIfUnused(env);
}
return napi_ok;
}
void js_run_env_cleanup_hooks(napi_env env) {
if (env == nullptr) {
return;
}
std::vector<std::pair<napi_cleanup_hook, void*>> env_hooks_to_run;
std::vector<napi_async_cleanup_hook_handle__*> async_hooks_to_run;
{
std::lock_guard<std::mutex> lock(g_cleanup_hooks_mutex);
auto state_it = g_cleanup_hooks.find(env);
if (state_it == g_cleanup_hooks.end()) {
return;
}
auto& state = state_it->second;
env_hooks_to_run.swap(state.env_hooks);
state.draining_async_hooks = true;
async_hooks_to_run = state.async_hooks;
}
for (auto it = env_hooks_to_run.rbegin(); it != env_hooks_to_run.rend(); ++it) {
if (it->first != nullptr) {
it->first(it->second);
}
}
for (auto it = async_hooks_to_run.rbegin(); it != async_hooks_to_run.rend(); ++it) {
auto* handle = *it;
napi_async_cleanup_hook hook = nullptr;
void* data = nullptr;
bool should_invoke = false;
{
std::lock_guard<std::mutex> lock(g_cleanup_hooks_mutex);
auto state_it = g_cleanup_hooks.find(env);
if (state_it == g_cleanup_hooks.end()) {
break;
}
auto& state = state_it->second;
auto vec_it =
std::find(state.async_hooks.begin(), state.async_hooks.end(), handle);
if (vec_it != state.async_hooks.end() && !handle->removed) {
hook = handle->hook;
data = handle->data;
should_invoke = true;
}
}
if (should_invoke && hook != nullptr) {
hook(handle, data);
}
}
std::vector<napi_async_cleanup_hook_handle__*> handles_to_delete;
{
std::unique_lock<std::mutex> lock(g_cleanup_hooks_mutex);
g_cleanup_hooks_cv.wait(lock, [&]() {
auto state_it = g_cleanup_hooks.find(env);
return state_it == g_cleanup_hooks.end() ||
state_it->second.async_hooks.empty();
});
auto state_it = g_cleanup_hooks.find(env);
if (state_it == g_cleanup_hooks.end()) {
return;
}
auto& state = state_it->second;
state.draining_async_hooks = false;
handles_to_delete.swap(state.deferred_delete_async_hooks);
if (IsCleanupStateEmpty(state)) {
g_cleanup_hooks.erase(state_it);
}
}
for (auto* handle : handles_to_delete) {
delete handle;
}
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_create_threadsafe_function(
napi_env env, napi_value func, napi_value async_resource,
napi_value async_resource_name, size_t max_queue_size,
size_t initial_thread_count, void* thread_finalize_data,
napi_finalize thread_finalize_cb, void* context,
napi_threadsafe_function_call_js call_js_cb,
napi_threadsafe_function* result) {
(void)async_resource;
(void)async_resource_name;
if (env == nullptr || result == nullptr || initial_thread_count == 0) {
return napi_invalid_arg;
}
auto* tsfn = new napi_threadsafe_function__();
tsfn->env = env;
tsfn->call_js_cb = call_js_cb;
tsfn->context = context;
tsfn->thread_finalize_data = thread_finalize_data;
tsfn->thread_finalize_cb = thread_finalize_cb;
tsfn->max_queue_size = max_queue_size;
tsfn->thread_count = initial_thread_count;
tsfn->run_loop = GetRuntimeRunLoop(env);
if (tsfn->run_loop != nullptr) {
CFRetain(tsfn->run_loop);
}
if (func != nullptr) {
napi_status status = napi_create_reference(env, func, 1, &tsfn->callback_ref);
if (status != napi_ok) {
if (tsfn->run_loop != nullptr) {
CFRelease(tsfn->run_loop);
}
delete tsfn;
return status;
}
}
*result = tsfn;
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_get_threadsafe_function_context(napi_threadsafe_function funcOpaque,
void** result) {
if (funcOpaque == nullptr || result == nullptr) {
return napi_invalid_arg;
}
auto* func = static_cast<napi_threadsafe_function__*>(funcOpaque);
*result = func->context;
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_call_threadsafe_function(napi_threadsafe_function funcOpaque, void* data,
napi_threadsafe_function_call_mode is_blocking) {
if (funcOpaque == nullptr) {
return napi_invalid_arg;
}
auto* tsfn = static_cast<napi_threadsafe_function__*>(funcOpaque);
{
std::unique_lock<std::mutex> lock(tsfn->mutex);
while (tsfn->max_queue_size > 0 &&
tsfn->queued_calls >= tsfn->max_queue_size && !tsfn->closing) {
if (is_blocking == napi_tsfn_nonblocking) {
return napi_queue_full;
}
if (CFRunLoopGetCurrent() == tsfn->run_loop) {
return napi_would_deadlock;
}
tsfn->queue_cv.wait(lock, [&]() {
return tsfn->closing ||
(tsfn->queued_calls < tsfn->max_queue_size);
});
}
if (tsfn->closing) {
return napi_closing;
}
tsfn->queued_calls++;
}
auto call = std::make_shared<TSFNCall>();
call->tsfn = tsfn;
call->data = data;
call->blocking = (is_blocking == napi_tsfn_blocking);
auto task = std::make_shared<std::function<void()>>(
[call]() { ExecuteTSFNCall(call); });
if (!ScheduleOnRunLoop(tsfn->run_loop, task)) {
{
std::lock_guard<std::mutex> lock(tsfn->mutex);
if (tsfn->queued_calls > 0) {
tsfn->queued_calls--;
}
}
tsfn->queue_cv.notify_all();
return napi_generic_failure;
}
if (call->blocking) {
std::unique_lock<std::mutex> lock(call->done_mutex);
call->done_cv.wait(lock, [&]() { return call->done; });
}
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_acquire_threadsafe_function(napi_threadsafe_function funcOpaque) {
if (funcOpaque == nullptr) {
return napi_invalid_arg;
}
auto* tsfn = static_cast<napi_threadsafe_function__*>(funcOpaque);
std::lock_guard<std::mutex> lock(tsfn->mutex);
if (tsfn->closing) {
return napi_closing;
}
tsfn->thread_count++;
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_release_threadsafe_function(
napi_threadsafe_function funcOpaque,
napi_threadsafe_function_release_mode mode) {
if (funcOpaque == nullptr) {
return napi_invalid_arg;
}
auto* tsfn = static_cast<napi_threadsafe_function__*>(funcOpaque);
{
std::lock_guard<std::mutex> lock(tsfn->mutex);
if (tsfn->thread_count == 0) {
return napi_closing;
}
if (mode == napi_tsfn_abort) {
tsfn->closing = true;
tsfn->thread_count = 0;
} else {
tsfn->thread_count--;
if (tsfn->thread_count == 0) {
tsfn->closing = true;
}
}
}
tsfn->queue_cv.notify_all();
ScheduleFinalizeIfNeeded(tsfn);
return napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function funcOpaque) {
(void)env;
return funcOpaque == nullptr ? napi_invalid_arg : napi_ok;
}
extern "C" NAPI_EXTERN napi_status NAPI_CDECL
napi_unref_threadsafe_function(napi_env env,
napi_threadsafe_function funcOpaque) {
(void)env;
return funcOpaque == nullptr ? napi_invalid_arg : napi_ok;
}