Repository navigation
Expand file tree
/
Copy pathCompilePool.cpp
More file actions
98 lines (85 loc) · 2.32 KB
/
Copy pathCompilePool.cpp
File metadata and controls
98 lines (85 loc) · 2.32 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
#include "loader/CompilePool.h"
#include <algorithm>
#include <thread>
#include <utility>
#include <vector>
#include "ns/Thread.h"
namespace nativescript::common::loader {
CompilePool& CompilePool::Shared() {
static CompilePool* pool = [] {
const unsigned cpus = std::thread::hardware_concurrency();
return new CompilePool(std::clamp(cpus > 1 ? cpus - 1 : 1u, 1u, 4u));
}();
return *pool;
}
CompilePool::CompilePool(unsigned maxThreads)
: maxThreads_(std::max(maxThreads, 1u)) {}
bool CompilePool::Post(const void* owner, size_t stackBytes, Job job) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (jobs_.size() >= idle_ && threads_ < maxThreads_ &&
StartThreadLocked(stackBytes)) {
threads_++;
}
if (threads_ == 0) {
return false;
}
jobs_.push_back(Entry{owner, std::move(job)});
}
available_.notify_one();
return true;
}
void CompilePool::Discard(const void* owner) {
std::vector<Job> discarded;
{
std::lock_guard<std::mutex> lock(mutex_);
for (auto it = jobs_.begin(); it != jobs_.end();) {
if (it->owner == owner) {
discarded.push_back(std::move(it->job));
it = jobs_.erase(it);
} else {
++it;
}
}
}
for (Job& job : discarded) {
job(false);
}
}
bool CompilePool::StartThreadLocked(size_t stackBytes) {
return StartThread(
ThreadSpec{"ns-esm-compile", stackBytes, ThreadPriority::kUserInitiated},
[this] { ThreadMain(); });
}
void CompilePool::ThreadMain() {
for (;;) {
Job job;
{
std::unique_lock<std::mutex> lock(mutex_);
idle_++;
available_.wait(lock, [this] { return !jobs_.empty(); });
idle_--;
job = std::move(jobs_.front().job);
jobs_.pop_front();
}
platform::RunJob([&job] { job(true); });
}
}
uint64_t FileJobSignal::Generation() {
std::lock_guard<std::mutex> lock(mutex_);
return generation_;
}
void FileJobSignal::Notify() {
{
std::lock_guard<std::mutex> lock(mutex_);
generation_++;
}
changed_.notify_all();
}
void FileJobSignal::WaitForChange(uint64_t seen,
std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lock(mutex_);
changed_.wait_for(lock, timeout,
[this, seen] { return generation_ != seen; });
}
} // namespace nativescript::common::loader