JobLimit makes two projects and one more for every 32 hardware threads
and builds them from nothing at once, each from a thread of its own, as
RunTests builds its tests, while it counts the threads of its own
process. A project is 69 sources: 64 that import nothing, half C and
half C++, then a module of two partitions, one importing the other,
with its implementation unit, and a main.cpp that imports the module.
It is the same size on every machine, so that no command of its build
grows with the machine. The builds together may add as many threads as
the machine has hardware threads, and have to add at least two where
there are two; every program is then run and has to print 995: what
its 64 C and C++ functions return and the module's Top(), which is
built on the two partitions' functions. On 5b75df3 it fails: on a
machine with 56 hardware threads, "3 builds of 207 sources in all ran
on 205 threads at once". The count sees the steps that are jobs. A link
is none: its Build() runs it through RunBuildCommand from a thread that
was there before the count, which does not tell whether the link waited
for a worker.
JobGroup drives pools of its own, of one to four workers. Twelve jobs on
three workers run three at once and no more; a job starts after the
ones it was added after, in a graph of four jobs and in one of 300; the
first error keeps a job that comes after it and the jobs added later
from starting, and so does Fail(); what a job throws is its error; a
chain gets through one worker; Run() runs its work on a worker, on the
calling thread when that is one, where a JobGroup is refused; and
leaving a group's scope waits for the job that runs and starts no
other. It also holds the process's pool to a worker per hardware thread.
308 lines
14 KiB
C++
308 lines
14 KiB
C++
// SPDX-License-Identifier: LGPL-3.0-only
|
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
|
|
|
import std;
|
|
import Crafter.Build;
|
|
using namespace Crafter;
|
|
|
|
// JobPool and JobGroup, which every build step runs on. A pool runs as many
|
|
// jobs at once as it has workers and no more; a job of a group starts when the
|
|
// jobs it was added after have finished; the first error keeps what has not
|
|
// started from starting; and nothing that waits for jobs does so on a worker,
|
|
// where it would keep from them the thread they need.
|
|
//
|
|
// The pools here are the test's own, of one to four workers, so what is
|
|
// counted does not depend on the machine. Build() runs on the process's pool:
|
|
// tests/JobLimit holds a whole build to that one.
|
|
|
|
namespace {
|
|
std::int32_t Failures = 0;
|
|
|
|
void Check(bool cond, std::string_view msg) {
|
|
if (!cond) {
|
|
std::println(std::cerr, "FAIL: {}", msg);
|
|
++Failures;
|
|
}
|
|
}
|
|
|
|
// Twelve jobs on three workers. Each holds its worker until three run at
|
|
// once, so the pool is seen to reach its limit however the threads are
|
|
// scheduled, and then a moment longer with the lock released, counted as
|
|
// running all the while: jobs a pool let in beyond its workers would be
|
|
// counted on top of the ones in that moment. A pool that never gets to
|
|
// three is waited on once, then given up on.
|
|
void RunsAsManyAsItHasWorkers() {
|
|
constexpr std::int32_t workers = 3;
|
|
constexpr std::int32_t count = 12;
|
|
JobPool pool(workers);
|
|
std::mutex mutex;
|
|
std::condition_variable changed;
|
|
std::int32_t running = 0;
|
|
std::int32_t peak = 0;
|
|
std::int32_t ran = 0;
|
|
bool gaveUp = false;
|
|
JobGroup jobs(pool);
|
|
for (std::int32_t i = 0; i < count; ++i) {
|
|
jobs.Add(std::format("gauge {}", i), [&]() -> std::string {
|
|
std::unique_lock lock(mutex);
|
|
++running;
|
|
peak = std::max(peak, running);
|
|
changed.notify_all();
|
|
if (!changed.wait_for(lock, std::chrono::seconds(20), [&] { return peak >= workers || gaveUp; })) gaveUp = true;
|
|
lock.unlock();
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
|
lock.lock();
|
|
--running;
|
|
++ran;
|
|
return {};
|
|
});
|
|
}
|
|
Check(jobs.Wait().empty(), "jobs that return nothing leave the group without an error");
|
|
Check(ran == count, std::format("every job runs: {} of {} did", ran, count));
|
|
Check(peak == workers, std::format("a pool of {} workers runs {} jobs at once, not {}", workers, workers, peak));
|
|
}
|
|
|
|
// a, then b and c, then d: each records when it runs. The ones that
|
|
// others wait for take a moment first, so a group that started everything
|
|
// at once would record them last.
|
|
void StartsAJobAfterTheOnesItComesAfter() {
|
|
JobPool pool(3);
|
|
std::mutex mutex;
|
|
std::vector<std::string> order;
|
|
const auto record = [&mutex, &order](std::string name, std::int32_t milliseconds) {
|
|
return [&mutex, &order, name = std::move(name), milliseconds]() -> std::string {
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
|
|
std::lock_guard lock(mutex);
|
|
order.push_back(name);
|
|
return {};
|
|
};
|
|
};
|
|
const auto position = [&order](std::string_view name) {
|
|
return std::ranges::find(order, name) - order.begin();
|
|
};
|
|
JobGroup jobs(pool);
|
|
const JobGroup::Job a = jobs.Add("a", record("a", 60));
|
|
const std::array<JobGroup::Job, 1> afterA = {a};
|
|
const JobGroup::Job b = jobs.Add("b", record("b", 30), afterA);
|
|
const JobGroup::Job c = jobs.Add("c", record("c", 0), afterA);
|
|
const std::array<JobGroup::Job, 2> afterBoth = {b, c};
|
|
const JobGroup::Job d = jobs.Add("d", record("d", 0), afterBoth);
|
|
Check(jobs.Wait().empty(), "the ordered jobs leave no error");
|
|
Check(order.size() == 4, std::format("all four ordered jobs run: {}", order));
|
|
Check(position("a") < position("b") && position("a") < position("c"), std::format("b and c start after a has finished: {}", order));
|
|
Check(position("b") < position("d") && position("c") < position("d"), std::format("d starts after both b and c have finished: {}", order));
|
|
|
|
// After jobs that finished long ago: nothing is left to release it,
|
|
// so it has to start by itself.
|
|
const std::array<JobGroup::Job, 2> afterDone = {a, d};
|
|
jobs.Add("e", record("e", 0), afterDone);
|
|
Check(jobs.Wait().empty() && order.size() == 5, std::format("a job added after finished jobs runs: {}", order));
|
|
|
|
bool refused = false;
|
|
try {
|
|
const std::array<JobGroup::Job, 1> afterNone = {JobGroup::Job(99)};
|
|
jobs.Add("f", record("f", 0), afterNone);
|
|
} catch (const std::out_of_range&) {
|
|
refused = true;
|
|
}
|
|
Check(refused, "a job cannot be added after one the group does not have");
|
|
Check(jobs.Wait().empty() && order.size() == 5, std::format("the refused job never runs: {}", order));
|
|
}
|
|
|
|
// Three hundred jobs on four workers, each after up to three picked among
|
|
// the ones added before it, the same pick every run: every job runs
|
|
// once, and none before a job it comes after has finished.
|
|
void KeepsTheOrderOfALargerGraph() {
|
|
constexpr std::int32_t count = 300;
|
|
JobPool pool(4);
|
|
std::vector<std::atomic<std::int32_t>> runs(count);
|
|
std::atomic<std::int32_t> early{0};
|
|
std::mt19937 random(20261112);
|
|
JobGroup jobs(pool);
|
|
std::vector<JobGroup::Job> added;
|
|
for (std::int32_t i = 0; i < count; ++i) {
|
|
std::vector<JobGroup::Job> after;
|
|
std::vector<std::int32_t> before;
|
|
for (std::int32_t pick = 0; i > 0 && pick < 3; ++pick) {
|
|
if (random() % 2 == 0) continue;
|
|
const std::int32_t chosen = static_cast<std::int32_t>(random() % static_cast<std::uint32_t>(i));
|
|
after.push_back(added[chosen]);
|
|
before.push_back(chosen);
|
|
}
|
|
added.push_back(jobs.Add(std::format("node {}", i), [&runs, &early, before = std::move(before), i]() -> std::string {
|
|
for (const std::int32_t earlier : before) {
|
|
if (runs[earlier].load() != 1) ++early;
|
|
}
|
|
++runs[i];
|
|
return {};
|
|
}, after));
|
|
}
|
|
Check(jobs.Wait().empty(), "the larger graph leaves no error");
|
|
const std::int64_t once = std::ranges::count_if(runs, [](const std::atomic<std::int32_t>& ran) { return ran.load() == 1; });
|
|
Check(once == count, std::format("each of {} jobs runs once: {} did", count, once));
|
|
Check(early.load() == 0, std::format("no job starts before the ones it comes after have finished: {} did", early.load()));
|
|
}
|
|
|
|
void TheFirstErrorStopsTheRest() {
|
|
JobPool pool(2);
|
|
{
|
|
JobGroup jobs(pool);
|
|
std::atomic<bool> dependentRan{false};
|
|
std::atomic<bool> lateRan{false};
|
|
const JobGroup::Job failing = jobs.Add("failing", [] { return std::string("boom"); });
|
|
const std::array<JobGroup::Job, 1> afterFailing = {failing};
|
|
jobs.Add("dependent", [&dependentRan]() -> std::string {
|
|
dependentRan = true;
|
|
return {};
|
|
}, afterFailing);
|
|
Check(jobs.Wait() == "boom", "Wait returns what the failed job returned");
|
|
Check(jobs.Failed(), "a group with a failed job has failed");
|
|
Check(!dependentRan, "a job that comes after a failed one does not run");
|
|
jobs.Add("late", [&lateRan]() -> std::string {
|
|
lateRan = true;
|
|
return {};
|
|
});
|
|
jobs.Add("second", [] { return std::string("second"); });
|
|
Check(jobs.Wait() == "boom", "the first error stays the group's error");
|
|
Check(!lateRan, "a job added to a failed group does not run");
|
|
}
|
|
{
|
|
JobGroup jobs(pool);
|
|
jobs.Add("thrower", []() -> std::string { throw std::runtime_error("bang"); });
|
|
const std::string error = jobs.Wait();
|
|
Check(error == "thrower: bang", std::format("what a job throws is its error, under its label: '{}'", error));
|
|
}
|
|
{
|
|
JobGroup jobs(pool);
|
|
std::atomic<bool> ran{false};
|
|
Check(!jobs.Failed(), "a new group has not failed");
|
|
jobs.Fail("outside");
|
|
jobs.Fail("again");
|
|
jobs.Add("after", [&ran]() -> std::string {
|
|
ran = true;
|
|
return {};
|
|
});
|
|
Check(jobs.Wait() == "outside", "Fail gives the group its error, the first time");
|
|
Check(!ran, "no job starts in a group failed from outside");
|
|
}
|
|
}
|
|
|
|
// One worker and jobs that wait for each other: a job held back costs no
|
|
// thread, so the chain gets through on the one there is.
|
|
void OneWorkerIsEnough() {
|
|
JobPool pool(1);
|
|
std::mutex mutex;
|
|
std::int32_t running = 0;
|
|
std::int32_t peak = 0;
|
|
std::vector<std::int32_t> order;
|
|
JobGroup jobs(pool);
|
|
std::vector<JobGroup::Job> previous;
|
|
for (std::int32_t i = 0; i < 6; ++i) {
|
|
const auto work = [&mutex, &running, &peak, &order, i]() -> std::string {
|
|
{
|
|
std::lock_guard lock(mutex);
|
|
++running;
|
|
peak = std::max(peak, running);
|
|
}
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
|
std::lock_guard lock(mutex);
|
|
--running;
|
|
order.push_back(i);
|
|
return {};
|
|
};
|
|
// Every second one independent of the chain.
|
|
const JobGroup::Job job = i % 2 == 0 ? jobs.Add(std::format("link {}", i), work, previous) : jobs.Add(std::format("free {}", i), work);
|
|
if (i % 2 == 0) previous = {job};
|
|
}
|
|
Check(jobs.Wait().empty(), "the chain on one worker leaves no error");
|
|
Check(order.size() == 6 && peak == 1, std::format("six jobs run one at a time on one worker: {} ran, {} at once", order.size(), peak));
|
|
const auto position = [&order](std::int32_t i) {
|
|
return std::ranges::find(order, i) - order.begin();
|
|
};
|
|
Check(position(0) < position(2) && position(2) < position(4), std::format("the chain runs in its order: {}", order));
|
|
}
|
|
|
|
void RunIsOneJob() {
|
|
JobPool pool(1);
|
|
const std::thread::id here = std::this_thread::get_id();
|
|
std::thread::id ranOn = here;
|
|
pool.Run([&ranOn] { ranOn = std::this_thread::get_id(); });
|
|
Check(ranOn != here, "Run runs the work on a worker and returns once it has");
|
|
|
|
bool rethrown = false;
|
|
try {
|
|
pool.Run([] { throw std::runtime_error("from the work"); });
|
|
} catch (const std::runtime_error& e) {
|
|
rethrown = std::string_view(e.what()) == "from the work";
|
|
}
|
|
Check(rethrown, "what the work throws, Run throws");
|
|
|
|
// On the pool's only worker: queued, the inner step would wait for
|
|
// the thread its caller holds.
|
|
std::thread::id outer;
|
|
std::thread::id inner;
|
|
JobGroup jobs(pool);
|
|
jobs.Add("outer", [&pool, &outer, &inner]() -> std::string {
|
|
outer = std::this_thread::get_id();
|
|
pool.Run([&inner] { inner = std::this_thread::get_id(); });
|
|
return {};
|
|
});
|
|
Check(jobs.Wait().empty() && outer == inner && outer != here, "Run on a worker of the pool runs the work on that worker");
|
|
|
|
// And a group there is refused, where it would have waited the same way.
|
|
jobs.Add("nested", [&pool]() -> std::string {
|
|
JobGroup nested(pool);
|
|
return {};
|
|
});
|
|
const std::string error = jobs.Wait();
|
|
Check(error.starts_with("nested: ") && error.contains("JobGroup"), std::format("a JobGroup on a worker of its own pool is refused: '{}'", error));
|
|
}
|
|
|
|
// Leaving the scope of a group without Wait(), as an early return does:
|
|
// the job that runs is waited for, the one behind it never starts. The
|
|
// scope is left once the first runs, and the first goes on until the
|
|
// group has failed, which is what its destructor does first, so the
|
|
// second cannot have started before.
|
|
void LeavingWaitsForWhatRuns() {
|
|
JobPool pool(1);
|
|
std::atomic<bool> firstStarted{false};
|
|
std::atomic<bool> firstFinished{false};
|
|
std::atomic<bool> secondRan{false};
|
|
{
|
|
JobGroup jobs(pool);
|
|
jobs.Add("first", [&jobs, &firstStarted, &firstFinished]() -> std::string {
|
|
firstStarted = true;
|
|
firstStarted.notify_all();
|
|
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(20);
|
|
while (!jobs.Failed() && std::chrono::steady_clock::now() < deadline) std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
|
firstFinished = true;
|
|
return {};
|
|
});
|
|
jobs.Add("second", [&secondRan]() -> std::string {
|
|
secondRan = true;
|
|
return {};
|
|
});
|
|
firstStarted.wait(false);
|
|
}
|
|
Check(firstFinished, "leaving a group waits for the job that is running");
|
|
Check(!secondRan, "leaving a group keeps the jobs that have not started from starting");
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
// The labels of a few dozen jobs say nothing here.
|
|
Progress::SetVerbosity(Progress::Verbosity::Quiet);
|
|
|
|
const std::uint32_t hardware = std::max(1u, std::thread::hardware_concurrency());
|
|
Check(JobPool::Process().Workers() == hardware, std::format("the process's pool has a worker per hardware thread: {} for {}", JobPool::Process().Workers(), hardware));
|
|
Check(JobPool(0).Workers() == 1, "a pool has at least one worker");
|
|
|
|
RunsAsManyAsItHasWorkers();
|
|
StartsAJobAfterTheOnesItComesAfter();
|
|
KeepsTheOrderOfALargerGraph();
|
|
TheFirstErrorStopsTheRest();
|
|
OneWorkerIsEnough();
|
|
RunIsOneJob();
|
|
LeavingWaitsForWhatRuns();
|
|
return Failures == 0 ? 0 : 1;
|
|
}
|