Repository navigation
Expand file tree
/
Copy paththread_pool.cc
More file actions
767 lines (623 loc) · 26.4 KB
/
Copy paththread_pool.cc
File metadata and controls
767 lines (623 loc) · 26.4 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
#include <nan.h>
#include "../include/context.h"
#include "../include/thread_pool.h"
#include <condition_variable>
#include <mutex>
#include <queue>
#include <thread>
#include <utility>
extern "C" {
#include <git2/sys/custom_tls.h>
}
using namespace std::placeholders;
namespace nodegit {
class Executor {
public:
struct Task {
enum Type { SHUTDOWN, WORK };
Task(Type initType)
: type(initType)
{}
Task(const Task &) = delete;
Task(Task &&) = delete;
Task &operator=(const Task &) = delete;
Task &operator=(Task &&) = delete;
// We must define a virtual destructor so that derived classes are castable
virtual ~Task() {}
Type type;
};
struct ShutdownTask : Task {
ShutdownTask()
: Task(SHUTDOWN)
{}
};
struct WorkTask : Task {
WorkTask(ThreadPool::Callback initCallback, Nan::AsyncResource *asyncResource, Nan::Global<v8::Value> *callbackErrorHandle)
: Task(WORK), asyncResource(asyncResource), callbackErrorHandle(callbackErrorHandle), callback(initCallback)
{}
Nan::AsyncResource *asyncResource;
Nan::Global<v8::Value> *callbackErrorHandle;
ThreadPool::Callback callback;
};
typedef std::function<void(ThreadPool::OnPostCallbackFn)> PostCallbackEventToOrchestratorFn;
typedef std::function<void()> PostCompletedEventToOrchestratorFn;
typedef std::function<std::unique_ptr<Task>()> TakeNextTaskFn;
struct Event {
enum Type { COMPLETED, CALLBACK_TYPE };
Event(Type initType)
: type(initType)
{}
Event(const Event &) = delete;
Event(Event &&) = delete;
Event &operator=(const Event &) = delete;
Event &operator=(Event &&) = delete;
Type type;
// We must define a virtual destructor so that derived classes are castable
virtual ~Event() {}
};
struct CompletedEvent : Event {
CompletedEvent()
: Event(COMPLETED)
{}
};
struct CallbackEvent : Event {
CallbackEvent(ThreadPool::OnPostCallbackFn initCallback)
: Event(CALLBACK_TYPE), callback(initCallback)
{}
ThreadPool::Callback operator()(ThreadPool::QueueCallbackFn queueCb, ThreadPool::Callback completedCb) {
return callback(queueCb, completedCb);
}
private:
ThreadPool::OnPostCallbackFn callback;
};
Executor(
PostCallbackEventToOrchestratorFn postCallbackEventToOrchestrator,
PostCompletedEventToOrchestratorFn postCompletedEventToOrchestrator,
TakeNextTaskFn takeNextTask,
nodegit::Context *context
);
void RunTaskLoop();
// Orchestrator needs to call this to ensure that the executor is done reading from
// the Orchestrator's memory
void WaitForThreadClose();
static Nan::AsyncResource *GetCurrentAsyncResource();
static const nodegit::Context *GetCurrentContext();
static Nan::Global<v8::Value> *GetCurrentCallbackErrorHandle();
static void PostCallbackEvent(ThreadPool::OnPostCallbackFn onPostCallback);
// Libgit2 will call this before it spawns a child thread.
// That way we can decide what the TLS for that thread should be
// We will make sure that the context for the current async work
// is preserved on the child thread through this method
static void *RetrieveTLSForLibgit2ChildThread();
// Libgit2 will call this on a child thread with the pointer that was
// retrieved from RetrieveTLSForLibgit2ChildThread. That allows us
// to store the necessary thread local storage for the child thread
static void SetTLSForLibgit2ChildThread(void *vexecutor);
// Called when a libgit2 child thread exits. This gives us the ability
// to teardown any TLS we set up for the child thread if we need to
static void TeardownTLSOnLibgit2ChildThread();
private:
Nan::AsyncResource *currentAsyncResource;
Nan::Global<v8::Value> *currentCallbackErrorHandle;
nodegit::Context *currentContext;
// We need to populate the executor on every thread that libgit2
// could make a callback on so that it can correctly queue callbacks
// in the correct javascript context
thread_local static Executor *executor;
thread_local static bool isExecutorThread;
PostCallbackEventToOrchestratorFn postCallbackEventToOrchestrator;
PostCompletedEventToOrchestratorFn postCompletedEventToOrchestrator;
TakeNextTaskFn takeNextTask;
std::thread thread;
};
Executor::Executor(
PostCallbackEventToOrchestratorFn postCallbackEventToOrchestrator,
PostCompletedEventToOrchestratorFn postCompletedEventToOrchestrator,
TakeNextTaskFn takeNextTask,
nodegit::Context *context
)
: currentAsyncResource(nullptr),
currentCallbackErrorHandle(nullptr),
currentContext(context),
postCallbackEventToOrchestrator(postCallbackEventToOrchestrator),
postCompletedEventToOrchestrator(postCompletedEventToOrchestrator),
takeNextTask(takeNextTask),
thread(&Executor::RunTaskLoop, this)
{}
void Executor::RunTaskLoop() {
// Set the thread local storage so that libgit2 can pick up the current executor
// for the thread.
isExecutorThread = true;
executor = this;
for ( ; ; ) {
std::unique_ptr<Task> task = takeNextTask();
if (task->type == Task::Type::SHUTDOWN) {
return;
}
WorkTask *workTask = static_cast<WorkTask *>(task.get());
currentAsyncResource = workTask->asyncResource;
currentCallbackErrorHandle = workTask->callbackErrorHandle;
workTask->callback();
currentCallbackErrorHandle = nullptr;
currentAsyncResource = nullptr;
postCompletedEventToOrchestrator();
}
}
void Executor::WaitForThreadClose() {
thread.join();
}
Nan::AsyncResource *Executor::GetCurrentAsyncResource() {
if (executor) {
return executor->currentAsyncResource;
}
// NOTE this should always be set when a libgit2 callback is running,
// so this case should not happen.
return nullptr;
}
const nodegit::Context *Executor::GetCurrentContext() {
if (executor) {
return executor->currentContext;
}
// NOTE this should always be set when a libgit2 callback is running,
// so this case should not happen.
return nullptr;
}
Nan::Global<v8::Value> *Executor::GetCurrentCallbackErrorHandle() {
if (executor) {
return executor->currentCallbackErrorHandle;
}
// NOTE this should always be set when a libgit2 callback is running,
// so this case should not happen.
return nullptr;
}
void Executor::PostCallbackEvent(ThreadPool::OnPostCallbackFn onPostCallback) {
if (executor) {
executor->postCallbackEventToOrchestrator(onPostCallback);
}
}
void *Executor::RetrieveTLSForLibgit2ChildThread() {
return Executor::executor;
}
void Executor::SetTLSForLibgit2ChildThread(void *vexecutor) {
Executor::executor = static_cast<Executor *>(vexecutor);
}
void Executor::TeardownTLSOnLibgit2ChildThread() {
if (!isExecutorThread) {
Executor::executor = nullptr;
}
}
thread_local Executor *Executor::executor = nullptr;
thread_local bool Executor::isExecutorThread = false;
class Orchestrator {
public:
struct Job {
enum Type { SHUTDOWN, ASYNC_WORK };
Job(Type initType)
: type(initType)
{}
Job(const Job &) = delete;
Job(Job &&) = delete;
Job &operator=(const Job &) = delete;
Job &operator=(Job &&) = delete;
virtual ~Job() {}
Type type;
};
struct ShutdownJob : Job {
ShutdownJob()
: Job(SHUTDOWN)
{}
};
struct AsyncWorkJob : Job {
AsyncWorkJob(nodegit::AsyncWorker *initWorker)
: Job(ASYNC_WORK), worker(initWorker)
{}
nodegit::AsyncWorker *worker;
};
typedef std::function<void(ThreadPool::Callback, ThreadPool::Callback, bool)> QueueCallbackOnJSThreadFn;
typedef std::function<std::shared_ptr<Job>()> TakeNextJobFn;
private:
class OrchestratorImpl {
public:
OrchestratorImpl(
QueueCallbackOnJSThreadFn queueCallbackOnJSThread,
TakeNextJobFn takeNextJob,
nodegit::Context *context
);
void RunJobLoop();
// The Executor will call this method to queue a CallbackEvent in Orchestrator's event loop
void PostCallbackEvent(ThreadPool::OnPostCallbackFn onPostCallback);
// The Executor will call this method after completion its work. This should queue
// a CompletedEvent in Thread's event loop
void PostCompletedEvent();
// This will be used by Executor to take jobs that the Thread has picked up and run them.
std::unique_ptr<Executor::Task> TakeNextTask();
// This is used to wait for the Orchestrator's thread to shutdown after signaling shutdown
void WaitForThreadClose();
private:
// The only thread safe way to pull events from executorEventsQueue
std::shared_ptr<Executor::Event> TakeEventFromExecutor();
void ScheduleWorkTaskOnExecutor(ThreadPool::Callback callback, Nan::AsyncResource *asyncResource, Nan::Global<v8::Value> *callbackErrorHandle);
void ScheduleShutdownTaskOnExecutor();
std::condition_variable taskCondition;
std::unique_ptr<std::mutex> taskMutex;
std::queue<std::shared_ptr<Executor::Event>> executorEventsQueue;
std::unique_ptr<std::mutex> executorEventsMutex;
std::condition_variable executorEventsCondition;
QueueCallbackOnJSThreadFn queueCallbackOnJSThread;
TakeNextJobFn takeNextJob;
std::unique_ptr<Executor::Task> task;
std::thread thread;
Executor executor;
};
std::unique_ptr<OrchestratorImpl> impl;
public:
Orchestrator(
QueueCallbackOnJSThreadFn queueCallbackOnJSThread,
TakeNextJobFn takeNextJob,
nodegit::Context *context
);
void WaitForThreadClose();
};
Orchestrator::OrchestratorImpl::OrchestratorImpl(
QueueCallbackOnJSThreadFn queueCallbackOnJSThread,
TakeNextJobFn takeNextJob,
nodegit::Context *context
)
: taskMutex(new std::mutex),
executorEventsMutex(new std::mutex),
queueCallbackOnJSThread(queueCallbackOnJSThread),
takeNextJob(takeNextJob),
task(nullptr),
thread(&Orchestrator::OrchestratorImpl::RunJobLoop, this),
executor(
std::bind(&Orchestrator::OrchestratorImpl::PostCallbackEvent, this, _1),
std::bind(&Orchestrator::OrchestratorImpl::PostCompletedEvent, this),
std::bind(&Orchestrator::OrchestratorImpl::TakeNextTask, this),
context
)
{}
void Orchestrator::OrchestratorImpl::RunJobLoop() {
for ( ; ; ) {
auto job = takeNextJob();
switch (job->type) {
case Job::Type::SHUTDOWN: {
ScheduleShutdownTaskOnExecutor();
executor.WaitForThreadClose();
return;
}
case Job::Type::ASYNC_WORK: {
std::shared_ptr<AsyncWorkJob> asyncWorkJob = std::static_pointer_cast<AsyncWorkJob>(job);
nodegit::AsyncWorker *worker = asyncWorkJob->worker;
// We lock at this level, because we temporarily unlock the lock master
// when a callback is fired. We need to be on the same thread to ensure
// the same thread that acquired the locks also releases them
nodegit::LockMaster lock = worker->AcquireLocks();
ScheduleWorkTaskOnExecutor(std::bind(&nodegit::AsyncWorker::Execute, worker), worker->GetAsyncResource(), worker->GetCallbackErrorHandle());
for ( ; ; ) {
std::shared_ptr<Executor::Event> event = TakeEventFromExecutor();
if (event->type == Executor::Event::Type::COMPLETED) {
break;
}
// We must have received a callback from libgit2
auto callbackEvent = std::static_pointer_cast<Executor::CallbackEvent>(event);
std::shared_ptr<std::mutex> callbackMutex(new std::mutex);
std::shared_ptr<std::condition_variable> callbackCondition(new std::condition_variable);
bool hasCompleted = false;
LockMaster::TemporaryUnlock temporaryUnlock;
auto onCompletedCallback = (*callbackEvent)(
[this](ThreadPool::Callback callback, ThreadPool::Callback cancelCallback) {
queueCallbackOnJSThread(callback, cancelCallback, false);
},
[callbackCondition, callbackMutex, &hasCompleted]() {
std::lock_guard<std::mutex> lock(*callbackMutex);
hasCompleted = true;
callbackCondition->notify_one();
}
);
std::unique_lock<std::mutex> lock(*callbackMutex);
while (!hasCompleted) callbackCondition->wait(lock);
onCompletedCallback();
}
queueCallbackOnJSThread(
[worker]() {
worker->WorkComplete();
worker->Destroy();
},
[worker]() {
worker->Cancel();
worker->WorkComplete();
worker->Destroy();
},
true
);
}
}
}
}
// TODO add a cancel callback to `OnPostCallbackFn` which can be used on nodegit terminate
void Orchestrator::OrchestratorImpl::PostCallbackEvent(ThreadPool::OnPostCallbackFn onPostCallback) {
std::lock_guard<std::mutex> lock(*executorEventsMutex);
std::shared_ptr<Executor::CallbackEvent> callbackEvent(new Executor::CallbackEvent(onPostCallback));
executorEventsQueue.push(callbackEvent);
executorEventsCondition.notify_one();
}
void Orchestrator::OrchestratorImpl::PostCompletedEvent() {
std::lock_guard<std::mutex> lock(*executorEventsMutex);
std::shared_ptr<Executor::CompletedEvent> completedEvent(new Executor::CompletedEvent);
executorEventsQueue.push(completedEvent);
executorEventsCondition.notify_one();
}
std::shared_ptr<Executor::Event> Orchestrator::OrchestratorImpl::TakeEventFromExecutor() {
std::unique_lock<std::mutex> lock(*executorEventsMutex);
while (executorEventsQueue.empty()) executorEventsCondition.wait(lock);
std::shared_ptr<Executor::Event> executorEvent = executorEventsQueue.front();
executorEventsQueue.pop();
return executorEvent;
}
void Orchestrator::OrchestratorImpl::ScheduleShutdownTaskOnExecutor() {
std::lock_guard<std::mutex> lock(*taskMutex);
task.reset(new Executor::ShutdownTask);
taskCondition.notify_one();
}
void Orchestrator::OrchestratorImpl::ScheduleWorkTaskOnExecutor(ThreadPool::Callback callback, Nan::AsyncResource *asyncResource, Nan::Global<v8::Value> *callbackErrorHandle) {
std::lock_guard<std::mutex> lock(*taskMutex);
task.reset(new Executor::WorkTask(callback, asyncResource, callbackErrorHandle));
taskCondition.notify_one();
}
std::unique_ptr<Executor::Task> Orchestrator::OrchestratorImpl::TakeNextTask() {
std::unique_lock<std::mutex> lock(*taskMutex);
while (!task) taskCondition.wait(lock);
return std::move(task);
}
void Orchestrator::OrchestratorImpl::WaitForThreadClose() {
thread.join();
}
Orchestrator::Orchestrator(
QueueCallbackOnJSThreadFn queueCallbackOnJSThread,
TakeNextJobFn takeNextJob,
nodegit::Context *context
)
: impl(new OrchestratorImpl(queueCallbackOnJSThread, takeNextJob, context))
{}
void Orchestrator::WaitForThreadClose() {
impl->WaitForThreadClose();
}
class ThreadPoolImpl {
public:
ThreadPoolImpl(int numberOfThreads, uv_loop_t *loop, nodegit::Context *context);
void QueueWorker(nodegit::AsyncWorker *worker);
std::shared_ptr<Orchestrator::Job> TakeNextJob();
void QueueCallbackOnJSThread(ThreadPool::Callback callback, ThreadPool::Callback cancelCallback, bool isWork);
static void RunJSThreadCallbacksFromOrchestrator(uv_async_t *handle);
void RunJSThreadCallbacksFromOrchestrator();
static void RunLoopCallbacks(uv_async_t *handle);
void Shutdown(std::unique_ptr<AsyncContextCleanupHandle> cleanupHandle);
struct AsyncCallbackData {
AsyncCallbackData(ThreadPoolImpl *pool)
: pool(pool)
{}
std::unique_ptr<AsyncContextCleanupHandle> cleanupHandle;
ThreadPoolImpl *pool;
};
private:
bool isMarkedForDeletion;
nodegit::Context *currentContext;
struct JSThreadCallback {
JSThreadCallback(ThreadPool::Callback callback, ThreadPool::Callback cancelCallback, bool isWork)
: isWork(isWork), callback(callback), cancelCallback(cancelCallback)
{}
JSThreadCallback()
: isWork(false), callback(nullptr), cancelCallback(nullptr)
{}
void performCallback() {
callback();
}
void cancel() {
cancelCallback();
}
bool isWork;
private:
ThreadPool::Callback callback;
ThreadPool::Callback cancelCallback;
};
void RunLoopCallbacks();
std::queue<std::shared_ptr<Orchestrator::Job>> orchestratorJobQueue;
std::unique_ptr<std::mutex> orchestratorJobMutex;
std::condition_variable orchestratorJobCondition;
size_t workInProgressCount;
// completion and async callbacks to be performed on the loop
std::queue<JSThreadCallback> jsThreadCallbackQueue;
std::unique_ptr<std::mutex> jsThreadCallbackMutex;
uv_async_t jsThreadCallbackAsync;
std::vector<Orchestrator> orchestrators;
};
ThreadPoolImpl::ThreadPoolImpl(int numberOfThreads, uv_loop_t *loop, nodegit::Context *context)
: isMarkedForDeletion(false),
currentContext(context),
orchestratorJobMutex(new std::mutex),
jsThreadCallbackMutex(new std::mutex)
{
uv_async_init(loop, &jsThreadCallbackAsync, RunLoopCallbacks);
jsThreadCallbackAsync.data = new AsyncCallbackData(this);
uv_unref((uv_handle_t *)&jsThreadCallbackAsync);
workInProgressCount = 0;
for (int i = 0; i < numberOfThreads; i++) {
orchestrators.emplace_back(
std::bind(&ThreadPoolImpl::QueueCallbackOnJSThread, this, _1, _2, _3),
std::bind(&ThreadPoolImpl::TakeNextJob, this),
context
);
}
}
void ThreadPoolImpl::QueueWorker(nodegit::AsyncWorker *worker) {
std::lock_guard<std::mutex> lock(*orchestratorJobMutex);
// there is work on the thread pool - reference the handle so
// node doesn't terminate
uv_ref((uv_handle_t *)&jsThreadCallbackAsync);
orchestratorJobQueue.emplace(new Orchestrator::AsyncWorkJob(worker));
workInProgressCount++;
orchestratorJobCondition.notify_one();
}
std::shared_ptr<Orchestrator::Job> ThreadPoolImpl::TakeNextJob() {
std::unique_lock<std::mutex> lock(*orchestratorJobMutex);
while (orchestratorJobQueue.empty()) orchestratorJobCondition.wait(lock);
auto orchestratorJob = orchestratorJobQueue.front();
// When the thread pool is shutting down, the thread pool will drain the work queue and replace it with
// a single shared_ptr to a shutdown job, so don't pop the queue when we're shutting down so
// everyone gets the signal
if (orchestratorJob->type != Orchestrator::Job::Type::SHUTDOWN) {
orchestratorJobQueue.pop();
}
return orchestratorJob;
}
void ThreadPoolImpl::QueueCallbackOnJSThread(ThreadPool::Callback callback, ThreadPool::Callback cancelCallback, bool isWork) {
std::unique_lock<std::mutex> lock(*jsThreadCallbackMutex);
// When the threadpool is shutting down, we want to free up the executors to also shutdown
// that means that we need to cancel all non-work callbacks as soon as we see them and
// we know that we are shutting down
if (isMarkedForDeletion && !isWork) {
// we don't know how long the cancelCallback will take, and it certainly doesn't need the lock
// while we're running it, so unlock it immediately.
lock.unlock();
cancelCallback();
return;
}
bool queueWasEmpty = jsThreadCallbackQueue.empty();
jsThreadCallbackQueue.emplace(callback, cancelCallback, isWork);
// we only trigger RunLoopCallbacks via the jsThreadCallbackAsync handle if the queue
// was empty. Otherwise, we depend on RunLoopCallbacks to re-trigger itself
if (queueWasEmpty) {
uv_async_send(&jsThreadCallbackAsync);
}
}
void ThreadPoolImpl::RunLoopCallbacks(uv_async_t* handle) {
auto asyncCallbackData = static_cast<AsyncCallbackData *>(handle->data);
if (asyncCallbackData->pool) {
asyncCallbackData->pool->RunLoopCallbacks();
}
}
// NOTE this should theoretically never be triggered during a cleanup operation
void ThreadPoolImpl::RunLoopCallbacks() {
Nan::HandleScope scope;
v8::Local<v8::Context> context = Nan::GetCurrentContext();
node::CallbackScope callbackScope(context->GetIsolate(), Nan::New<v8::Object>(), {0, 0});
std::unique_lock<std::mutex> lock(*jsThreadCallbackMutex);
// get the next callback to run
JSThreadCallback jsThreadCallback = jsThreadCallbackQueue.front();
jsThreadCallbackQueue.pop();
lock.unlock();
jsThreadCallback.performCallback();
lock.lock();
if (!jsThreadCallbackQueue.empty()) {
uv_async_send(&jsThreadCallbackAsync);
}
// if there is no ongoing work / completion processing, node doesn't need
// to be prevented from terminating
if (jsThreadCallback.isWork) {
std::lock_guard<std::mutex> orchestratorLock(*orchestratorJobMutex);
workInProgressCount--;
if (!workInProgressCount) {
uv_unref((uv_handle_t *)&jsThreadCallbackAsync);
}
}
}
void ThreadPoolImpl::Shutdown(std::unique_ptr<AsyncContextCleanupHandle> cleanupHandle) {
std::queue<std::shared_ptr<Orchestrator::Job>> cancelledJobs;
std::queue<JSThreadCallback> cancelledCallbacks;
{
std::unique_lock<std::mutex> orchestratorLock(*orchestratorJobMutex, std::defer_lock);
std::unique_lock<std::mutex> jsThreadLock(*jsThreadCallbackMutex, std::defer_lock);
std::lock(orchestratorLock, jsThreadLock);
// Once we've marked for deletion, we will start cancelling all callbacks
// when an attempt to queue a callback is made
isMarkedForDeletion = true;
// We want to grab all of the jobs that have been queued and run their cancel routines
// so that we can clean up their resources
orchestratorJobQueue.swap(cancelledJobs);
// We also want to grab all callbacks that have been queued so that we can
// run their cancel routines, this will help terminate the async workers
// that are currently being executed complete so that the threads
// running them can exit cleanly
jsThreadCallbackQueue.swap(cancelledCallbacks);
// Pushing a ShutdownJob into the queue will instruct all threads
// to start their shutdown process when they see the job is available.
orchestratorJobQueue.emplace(new Orchestrator::ShutdownJob);
if (workInProgressCount) {
// unref the jsThreadCallback for all work in progress
// it will not be used after this function has completed
while (workInProgressCount--) {
uv_unref((uv_handle_t *)&jsThreadCallbackAsync);
}
}
orchestratorJobCondition.notify_all();
}
Nan::HandleScope scope;
v8::Local<v8::Context> context = Nan::GetCurrentContext();
node::CallbackScope callbackScope(context->GetIsolate(), Nan::New<v8::Object>(), {0, 0});
while (cancelledJobs.size()) {
std::shared_ptr<Orchestrator::Job> cancelledJob = cancelledJobs.front();
std::shared_ptr<Orchestrator::AsyncWorkJob> asyncWorkJob = std::static_pointer_cast<Orchestrator::AsyncWorkJob>(cancelledJob);
asyncWorkJob->worker->Cancel();
asyncWorkJob->worker->WorkComplete();
asyncWorkJob->worker->Destroy();
cancelledJobs.pop();
}
// We need to cancel all callbacks that were scheduled before the shutdown
// request went through. This will help finish any work any currently operating
// executors are undertaking
while (cancelledCallbacks.size()) {
JSThreadCallback cancelledCallback = cancelledCallbacks.front();
cancelledCallback.cancel();
cancelledCallbacks.pop();
}
std::for_each(orchestrators.begin(), orchestrators.end(), [](Orchestrator &orchestrator) {
orchestrator.WaitForThreadClose();
});
// After we have completed waiting for all threads to close
// we will need to cleanup the rest of the completion callbacks
// from workers that were still running when the shutdown signal
// was sent
std::lock_guard<std::mutex> jsThreadLock(*jsThreadCallbackMutex);
while (jsThreadCallbackQueue.size()) {
JSThreadCallback jsThreadCallback = jsThreadCallbackQueue.front();
jsThreadCallback.cancel();
jsThreadCallbackQueue.pop();
}
AsyncCallbackData *asyncCallbackData = static_cast<AsyncCallbackData *>(jsThreadCallbackAsync.data);
asyncCallbackData->cleanupHandle.swap(cleanupHandle);
asyncCallbackData->pool = nullptr;
uv_close(reinterpret_cast<uv_handle_t *>(&jsThreadCallbackAsync), [](uv_handle_t *handle) {
auto asyncCallbackData = static_cast<AsyncCallbackData *>(handle->data);
delete asyncCallbackData;
});
}
ThreadPool::ThreadPool(int numberOfThreads, uv_loop_t *loop, nodegit::Context *context)
: impl(new ThreadPoolImpl(numberOfThreads, loop, context))
{}
ThreadPool::~ThreadPool() {}
void ThreadPool::QueueWorker(nodegit::AsyncWorker *worker) {
impl->QueueWorker(worker);
}
void ThreadPool::PostCallbackEvent(OnPostCallbackFn onPostCallback) {
Executor::PostCallbackEvent(onPostCallback);
}
Nan::AsyncResource *ThreadPool::GetCurrentAsyncResource() {
return Executor::GetCurrentAsyncResource();
}
const nodegit::Context *ThreadPool::GetCurrentContext() {
return Executor::GetCurrentContext();
}
Nan::Global<v8::Value> *ThreadPool::GetCurrentCallbackErrorHandle() {
return Executor::GetCurrentCallbackErrorHandle();
}
void ThreadPool::Shutdown(std::unique_ptr<AsyncContextCleanupHandle> cleanupHandle) {
impl->Shutdown(std::move(cleanupHandle));
}
void ThreadPool::InitializeGlobal() {
git_custom_tls_set_callbacks(
Executor::RetrieveTLSForLibgit2ChildThread,
Executor::SetTLSForLibgit2ChildThread,
Executor::TeardownTLSOnLibgit2ChildThread
);
}
}