Brings the agent-work branch tip onto master, keeping master's architecture and putting every agent-work feature on top of it: the window/GpuDevice/ RenderTarget split, explicit per-instance profilers instead of a global, the input layer with scroll sources and ends, the Widgets core and components (shared SelectionModel/Commands lists, popup stack, titled panels, prompt dialogs, file browser, kanban, outline tree, markdown, docking), the gallery on the new UI, the Objects explorer and interpreter fixes, the Taskboard, the Sketch2D render path and its tests and bench, and the headless Wayland runner the UI tests drive. No MODULES_BUILD_* switches are introduced: platform differences are plain if (ANDROID) / if (NOT ANDROID).
82 lines
1.7 KiB
C++
82 lines
1.7 KiB
C++
#include "ParallelFor.hpp"
|
|
|
|
namespace tp {
|
|
|
|
ParallelFor::ParallelFor(size_t threads, ThreadStart onStart) :
|
|
mOnStart(std::move(onStart)) {
|
|
for (size_t index = 1; index < threads; index++)
|
|
mThreads.emplace_back([this, index]() {
|
|
if (mOnStart) mOnStart(index);
|
|
{
|
|
std::lock_guard lock(mMutex);
|
|
mStarted++;
|
|
}
|
|
mDone.notify_one();
|
|
work(0);
|
|
});
|
|
|
|
std::unique_lock lock(mMutex);
|
|
mDone.wait(lock, [this]() { return mStarted == mThreads.size(); });
|
|
}
|
|
|
|
ParallelFor::~ParallelFor() {
|
|
{
|
|
std::lock_guard lock(mMutex);
|
|
mStopping = true;
|
|
}
|
|
mStart.notify_all();
|
|
for (std::thread& thread : mThreads)
|
|
thread.join();
|
|
}
|
|
|
|
void ParallelFor::drain() {
|
|
while (true) {
|
|
const size_t index = mNext.fetch_add(1, std::memory_order_relaxed);
|
|
if (index >= mCount) return;
|
|
(*mBody)(index);
|
|
}
|
|
}
|
|
|
|
void ParallelFor::work(size_t seen) {
|
|
while (true) {
|
|
{
|
|
std::unique_lock lock(mMutex);
|
|
mStart.wait(lock, [&]() { return mStopping || (mGeneration != seen && mBody); });
|
|
if (mStopping) return;
|
|
seen = mGeneration;
|
|
mBusy++;
|
|
}
|
|
drain();
|
|
bool last = false;
|
|
{
|
|
std::lock_guard lock(mMutex);
|
|
last = --mBusy == 0;
|
|
}
|
|
if (last) mDone.notify_one();
|
|
}
|
|
}
|
|
|
|
void ParallelFor::run(size_t count, const std::function<void(size_t)>& body) {
|
|
if (count == 0) return;
|
|
if (mThreads.empty() || count == 1) {
|
|
for (size_t index = 0; index < count; index++)
|
|
body(index);
|
|
return;
|
|
}
|
|
|
|
{
|
|
std::lock_guard lock(mMutex);
|
|
mBody = &body;
|
|
mCount = count;
|
|
mNext.store(0, std::memory_order_relaxed);
|
|
mGeneration++;
|
|
}
|
|
mStart.notify_all();
|
|
drain();
|
|
|
|
std::unique_lock lock(mMutex);
|
|
mDone.wait(lock, [this]() { return mBusy == 0; });
|
|
mBody = nullptr;
|
|
mCount = 0;
|
|
}
|
|
}
|