forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.cpp
More file actions
57 lines (47 loc) · 1.27 KB
/
Queue.cpp
File metadata and controls
57 lines (47 loc) · 1.27 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
#include "Queue.h"
#include "_CJavaScriptEventLoop.h"
using namespace swift;
/// Get the next-in-queue storage slot.
static Job *&nextInQueue(Job *cur) {
return reinterpret_cast<Job*&>(cur->SchedulerPrivate);
}
Job *Queue::claimNext() {
if (auto job = this->HeadJob) {
this->HeadJob = nextInQueue(job);
return job;
}
return nullptr;
}
Queue::Queue() : HeadJob(nullptr), isSpinning(false) {
this->Context = (EventLoopContext) {
.Queue = this,
.Promise = nullptr,
};
}
void runEnqueuedJobs(EventLoopContext *context) {
Queue *queue = (Queue *)(context->Queue);
assert(queue->isSpinning);
while (auto *job = queue->claimNext()) {
job->run(ExecutorRef::generic());
}
queue->isSpinning = false;
}
void Queue::insertJob(swift::Job *newJob) {
Job **position = &HeadJob;
while (auto cur = *position) {
// If we find a job with lower priority, insert here.
if (cur->getPriority() < newJob->getPriority()) {
nextInQueue(newJob) = cur;
*position = newJob;
return;
}
// Otherwise, keep advancing through the queue.
position = &nextInQueue(cur);
}
nextInQueue(newJob) = nullptr;
*position = newJob;
if (!isSpinning) {
isSpinning = true;
registerEventLoopHook(runEnqueuedJobs, &this->Context);
}
}