18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-03 06:35:21 +01:00

perf(physics): the worker threads look out for the next job before they sleep, and wake one another

Each job of worker_pool released the semaphore of every thread it wanted from the calling thread, and the threads
slept again right after it. A frame of the test mode runs four or five jobs (the neighbours, the facts, the steps,
the hose exchange), so the main thread made some 40 wake calls a frame: 3.3 % of its time on Tomaszewo, and on
linia 107 it waited 4.8 % of its time for threads woken late.

Now a thread done with a job looks out for the next one for 50 us (spin_time), as the jobs of a frame come close
after one another, and only then sleeps. A job is a ticket (its number and the seats left for the threads of the
pool): the threads looking out take a seat each, and sleeping ones are woken for the seats left, two by the calling
thread and two more by each thread which takes a seat, so the wakes go out as a tree. A thread going to sleep sets
its flag before a last look at the ticket, and a waker takes the flag before it releases, so no job is missed and no
semaphore released twice. The calling thread closes the seats nobody took once it is done, then waits for the
threads which took one, looking out for them for a while before it sleeps on the count.

Which thread does which index never mattered for the results, so they don't change. workerpool.cpp moved into the
core library, for the new unit tests (each index once with any number of threads, jobs back to back and after the
threads slept, the threads of the pool taking part, an exception passed on).
This commit is contained in:
jerrrrycho
2026-12-02 06:15:59 +01:00
parent 75efb467db
commit 9cc1eb48a4
4 changed files with 295 additions and 43 deletions
+1 -1
View File
@@ -132,7 +132,6 @@ set(SOURCES
"model/Texture.cpp"
"utilities/Timer.cpp"
"utilities/asciiname.cpp"
"utilities/workerpool.cpp"
"utilities/memorystats.cpp"
"world/Track.cpp"
"world/TrackSleepers.cpp"
@@ -823,6 +822,7 @@ set(CORE_SOURCES
"utilities/logfiles.cpp"
"utilities/parser.cpp"
"utilities/utilities.cpp"
"utilities/workerpool.cpp"
"utilities/hardwareinfo.cpp"
"scene/sn_utils.cpp"
"scene/regionfile.cpp"
+137
View File
@@ -0,0 +1,137 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
// the pool of threads the vehicle physics splits its work over (worker_pool): each index of a job done once, whichever
// threads take part, jobs close after one another and after the threads went to sleep, and an exception passed on
#include "stdafx.h"
#include "utilities/workerpool.h"
#include "utilities/Globals.h"
#include "doctest.h"
#include <algorithm>
#include <atomic>
#include <numeric>
#include <stdexcept>
#include <thread>
#include <vector>
namespace
{
// Global.performance_multithreading on for the test, as it was after it
struct multithreading_on
{
bool const was{Global.performance_multithreading};
multithreading_on() { Global.performance_multithreading = true; }
~multithreading_on() { Global.performance_multithreading = was; }
multithreading_on(multithreading_on const &) = delete;
multithreading_on &operator=(multithreading_on const &) = delete;
};
// runs a job on the pool and tells whether each of its indices was done exactly once
bool each_once(worker_pool &Pool, std::size_t const Count, std::size_t const Threads)
{
std::vector<std::atomic<int>> calls(Count);
Pool.run(Count, Threads, [&](std::size_t const Index) { calls[Index].fetch_add(1, std::memory_order_relaxed); });
return std::ranges::all_of(calls, [](std::atomic<int> const &Calls) { return Calls.load() == 1; });
}
} // namespace
TEST_CASE("worker pool: each index of a job is done once, by any number of threads")
{
multithreading_on const multithreading;
worker_pool pool;
auto const cores{worker_pool::capacity()};
for (std::size_t const threads : {std::size_t{1}, std::size_t{2}, std::size_t{3}, cores, cores + 5})
{
for (std::size_t const count : {std::size_t{0}, std::size_t{1}, std::size_t{2}, std::size_t{7}, std::size_t{64}, std::size_t{1000}})
{
CAPTURE(threads);
CAPTURE(count);
CHECK(each_once(pool, count, threads));
}
}
CHECK(pool.size() <= cores);
}
TEST_CASE("worker pool: jobs right after one another, and after the threads went to sleep")
{
multithreading_on const multithreading;
worker_pool pool;
auto const threads{worker_pool::capacity()};
// back to back, as the jobs of a frame come: the threads still look out for the next one
auto failures{0};
for (int job = 0; job < 2000; ++job)
{
if (false == each_once(pool, 1 + job % 97, 2 + job % threads))
{
++failures;
}
}
CHECK(failures == 0);
// with pauses longer than the threads look out for a job: they sleep, and are woken
for (int job = 0; job < 20; ++job)
{
std::this_thread::sleep_for(worker_pool::spin_time * 4);
CHECK(each_once(pool, 500, threads));
}
}
TEST_CASE("worker pool: the threads of the pool take part in the work")
{
multithreading_on const multithreading;
if (worker_pool::capacity() < 2)
{
return;
}
worker_pool pool;
// a job of two calls which wait for each other: it ends only if a thread of the pool takes one of them
std::atomic<int> arrived{0};
pool.run(2, 2, [&](std::size_t) {
arrived.fetch_add(1);
while (arrived.load() < 2)
{
std::this_thread::yield();
}
});
CHECK(arrived.load() == 2);
// and again once it went to sleep
std::this_thread::sleep_for(worker_pool::spin_time * 4);
arrived = 0;
pool.run(2, 2, [&](std::size_t) {
arrived.fetch_add(1);
while (arrived.load() < 2)
{
std::this_thread::yield();
}
});
CHECK(arrived.load() == 2);
}
TEST_CASE("worker pool: an exception of the work is passed on once the other calls are done, and the pool works on")
{
multithreading_on const multithreading;
worker_pool pool;
auto const threads{worker_pool::capacity()};
std::atomic<int> calls{0};
CHECK_THROWS_AS(pool.run(100, threads,
[&](std::size_t const Index) {
calls.fetch_add(1);
if (Index == 10)
{
throw std::runtime_error("work failed");
}
}),
std::runtime_error);
CHECK(calls.load() <= 100);
CHECK(each_once(pool, 300, threads));
}
+131 -31
View File
@@ -14,13 +14,45 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/utilities.h"
#include <random>
#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
#define EU07_WORKER_PAUSE() _mm_pause()
#else
#define EU07_WORKER_PAUSE() std::this_thread::yield()
#endif
namespace
{
// a while of looking out for something: true once Time is up, the clock read each 64 calls only
class spin_budget
{
public:
explicit spin_budget(std::chrono::microseconds const Time) : m_until{std::chrono::steady_clock::now() + Time} {}
bool spent()
{
EU07_WORKER_PAUSE();
return ((++m_turns & 63u) == 0) && std::chrono::steady_clock::now() >= m_until;
}
private:
std::chrono::steady_clock::time_point m_until;
unsigned m_turns{0};
};
} // namespace
worker_pool::~worker_pool()
{
m_stop = true;
// a job of no seats, which the threads looking out for one see, and the sleeping ones are woken for
m_ticket.store(((m_ticket.load() >> seat_bits) + 1) << seat_bits);
for (auto &data : m_threads)
{
data->start.release();
if (data->sleeping.exchange(false))
{
data->start.release();
}
}
for (auto &data : m_threads)
{
@@ -39,17 +71,19 @@ std::size_t worker_pool::capacity()
void worker_pool::grow(std::size_t const Workers)
{
// no thread of the pool takes part in a job now, nor looks at the threads
m_threads.reserve(Workers);
auto const seen{m_ticket.load() >> seat_bits};
while (m_threads.size() < Workers)
{
auto &data{*m_threads.emplace_back(std::make_unique<thread_data>())};
data.thread = std::thread(&worker_pool::worker, this, std::ref(data));
data.thread = std::thread(&worker_pool::worker, this, std::ref(data), seen);
}
}
void worker_pool::run(std::size_t const Count, std::size_t const Threads, std::function<void(std::size_t)> const &Work)
{
auto const threads{std::min({Threads, capacity(), Count})};
auto const threads{std::min({Threads, capacity(), Count, static_cast<std::size_t>(seat_mask)})};
if (threads <= 1)
{
for (std::size_t index = 0; index < Count; ++index)
@@ -60,34 +94,70 @@ void worker_pool::run(std::size_t const Count, std::size_t const Threads, std::f
}
grow(threads - 1);
// the job is set before its ticket: the threads take it from there
m_work = &Work;
m_count = Count;
m_next.store(0, std::memory_order_relaxed);
m_finished.store(0, std::memory_order_relaxed);
{
std::scoped_lock lock(m_mutex);
m_work = &Work;
m_count = Count;
m_next = 0;
m_busy = threads - 1;
m_exception = nullptr;
}
// the job is set before the threads are woken: the semaphores pass it on to them
for (std::size_t thread = 0; thread < threads - 1; ++thread)
{
m_threads[thread]->start.release();
}
auto const seats{static_cast<std::uint64_t>(threads - 1)};
auto const job{(m_ticket.load(std::memory_order_relaxed) >> seat_bits) + 1};
m_ticket.store((job << seat_bits) | seats);
wake(job, 2);
// the calling thread works too
work(Work, Count);
std::unique_lock lock(m_mutex);
m_done.wait(lock, [this]() { return m_busy == 0; });
m_work = nullptr;
if (m_exception)
// the seats nobody took are closed, then the threads which took one are waited for
auto ticket{m_ticket.load()};
while (false == m_ticket.compare_exchange_weak(ticket, job << seat_bits))
{
}
auto const joined{static_cast<std::size_t>(seats - (ticket & seat_mask))};
spin_budget budget{spin_time};
for (auto finished{m_finished.load(std::memory_order_acquire)}; finished != joined; finished = m_finished.load(std::memory_order_acquire))
{
if (budget.spent())
{
m_finished.wait(finished, std::memory_order_acquire);
}
}
m_work = nullptr;
std::exception_ptr exception;
{
std::scoped_lock lock(m_mutex);
std::swap(exception, m_exception);
}
if (exception)
{
auto const exception{m_exception};
m_exception = nullptr;
lock.unlock();
std::rethrow_exception(exception);
}
}
void worker_pool::wake(std::uint64_t const Job, std::size_t Count)
{
for (auto &data : m_threads)
{
if (Count == 0)
{
return;
}
auto const ticket{m_ticket.load()};
if ((ticket >> seat_bits) != Job || (ticket & seat_mask) == 0)
{
return;
}
// the flag taken by one waker only: one release for each sleep
if (data->sleeping.load() && data->sleeping.exchange(false))
{
data->start.release();
--Count;
}
}
}
void worker_pool::work(std::function<void(std::size_t)> const &Work, std::size_t const Count)
{
try
@@ -109,7 +179,32 @@ void worker_pool::work(std::function<void(std::size_t)> const &Work, std::size_t
}
}
void worker_pool::worker(thread_data &Data)
std::uint64_t worker_pool::next_job(thread_data &Data, std::uint64_t const Seen)
{
auto ticket{m_ticket.load(std::memory_order_acquire)};
spin_budget budget{spin_time};
while ((ticket >> seat_bits) == Seen)
{
if (false == budget.spent())
{
ticket = m_ticket.load(std::memory_order_acquire);
continue;
}
// to sleep: the flag first, then a last look. a job set after it finds the flag and wakes the thread, one set before it
// is seen here. a waker which took the flag meanwhile has released the semaphore, which is taken then
Data.sleeping.store(true);
ticket = m_ticket.load();
if ((ticket >> seat_bits) == Seen || false == Data.sleeping.exchange(false))
{
Data.start.acquire();
}
ticket = m_ticket.load(std::memory_order_acquire);
budget = spin_budget{spin_time};
}
return ticket;
}
void worker_pool::worker(thread_data &Data, std::uint64_t Seen)
{
// draws of Random() in this thread go to an engine of its own: the one of the simulation can't be shared between threads
std::mt19937 randomengine(static_cast<std::mt19937::result_type>(true_random_seed())); // NOSONAR: randomness of the simulation, not of anything security-relevant
@@ -117,25 +212,30 @@ void worker_pool::worker(thread_data &Data)
while (true)
{
Data.start.acquire();
auto ticket{next_job(Data, Seen)};
Seen = ticket >> seat_bits;
if (m_stop)
{
break;
}
std::function<void(std::size_t)> const *job{nullptr};
std::size_t count{0};
// a seat of the job, while there are any: the job stays as it is until the thread is done with it
auto seated{false};
while ((ticket >> seat_bits) == Seen && (ticket & seat_mask) > 0)
{
std::scoped_lock lock(m_mutex);
job = m_work;
count = m_count;
if (m_ticket.compare_exchange_weak(ticket, ticket - 1))
{
seated = true;
break;
}
}
work(*job, count);
if (false == seated)
{
std::scoped_lock lock(m_mutex);
--m_busy;
// notified under the lock: the job and the pool stay as they are until the caller sees the count
m_done.notify_one();
continue;
}
wake(Seen, 2);
work(*m_work, m_count);
m_finished.fetch_add(1, std::memory_order_release);
m_finished.notify_one();
}
set_thread_random_engine(nullptr);
}
+26 -11
View File
@@ -10,8 +10,9 @@ http://mozilla.org/MPL/2.0/.
#pragma once
#include <atomic>
#include <condition_variable>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <functional>
#include <memory>
@@ -22,8 +23,10 @@ http://mozilla.org/MPL/2.0/.
// threads for work split into independent parts (Global.performance_multithreading). each job says how many threads its work is
// worth, up to all the logical cores of the machine; the thread which asks for the work takes part in it too. the threads are
// made when a job asks for more of them than there are, and wait between the jobs: a job wakes as many of them as it wants, each
// by a semaphore of its own
// made when a job asks for more of them than there are. between the jobs a thread looks out for the next one for a while
// (spin_time), as the jobs of a frame come close after one another, then sleeps on a semaphore of its own. a job takes the
// threads which look out for it, and wakes sleeping ones for the seats left: the asking thread wakes two at most, and each
// thread which takes a seat wakes two more, so that no thread wakes them all one after another
class worker_pool
{
public:
@@ -43,28 +46,40 @@ class worker_pool
{
return m_threads.size() + 1;
}
// how long a thread looks out for the next job before it sleeps
static constexpr std::chrono::microseconds spin_time{50};
private:
struct thread_data
struct alignas(64) thread_data
{
std::binary_semaphore start{0}; // released for each job the thread takes part in, and to stop it
std::binary_semaphore start{0}; // released to wake the thread from its sleep
std::atomic<bool> sleeping{false}; // set by the thread before it sleeps, taken by the one which wakes it
std::thread thread;
};
// the ticket of a job: its number in the upper bits, the seats left for the threads of the pool in the lower ones
static constexpr unsigned seat_bits{16};
static constexpr std::uint64_t seat_mask{(std::uint64_t{1} << seat_bits) - 1};
// makes threads up to the given count
void grow(std::size_t const Workers);
void worker(thread_data &Data);
// Seen: the number of the last job before the thread was made, which isn't for it
void worker(thread_data &Data, std::uint64_t Seen);
// the ticket of the first job after the one numbered Seen: looked out for, then slept for
std::uint64_t next_job(thread_data &Data, std::uint64_t const Seen);
// wakes up to Count sleeping threads while the job of the ticket has seats left
void wake(std::uint64_t const Job, std::size_t Count);
// takes the indices left of the current job
void work(std::function<void(std::size_t)> const &Work, std::size_t const Count);
std::vector<std::unique_ptr<thread_data>> m_threads;
std::mutex m_mutex;
std::condition_variable m_done;
// the current job, set before the threads are woken for it
std::mutex m_mutex; // of m_exception
// the current job, set before its ticket is
std::function<void(std::size_t)> const *m_work{nullptr};
std::size_t m_count{0};
std::atomic<std::size_t> m_next{0};
std::size_t m_busy{0}; // threads of the pool woken for it which aren't done
alignas(64) std::atomic<std::uint64_t> m_ticket{0};
alignas(64) std::atomic<std::size_t> m_next{0};
alignas(64) std::atomic<std::size_t> m_finished{0}; // threads of the pool done with the current job
std::exception_ptr m_exception;
std::atomic<bool> m_stop{false};
};