From 604bc400211ba3f298cbfef8195cd5cb1f68b595 Mon Sep 17 00:00:00 2001 From: Alug Date: Mon, 23 Jun 2025 20:06:09 +0200 Subject: [PATCH] add "for_each" to srb2 threadpool this exectures something for EACH thread not some abritatrily choosen ones --- src/core/thread_pool.h | 55 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/src/core/thread_pool.h b/src/core/thread_pool.h index 75961614e..535e77a9f 100644 --- a/src/core/thread_pool.h +++ b/src/core/thread_pool.h @@ -80,6 +80,7 @@ public: /// Enqueue but don't notify template void schedule(T&& thunk); + template void for_each(F&& task); /// Notify threads after several schedules void notify(); void notify_sema(const Sema& sema); @@ -143,6 +144,60 @@ void ThreadPool::schedule(T&& thunk) } } +template +void ThreadPool::for_each(F&& thunk) +{ + static_assert(sizeof(std::decay_t) <= sizeof(std::declval().raw)); + + if (immediate_mode_) + { + thunk(); + return; + } + + Sema sync_sema; + begin_sema(); + + auto counter = std::make_shared>(threads_.size()); + + for (size_t i = 0; i < threads_.size(); i++) { + std::shared_ptr q = work_queues_[i]; + Task task; + + struct TaskData { + std::decay_t func; + std::shared_ptr> counter; + Sema sema; + ThreadPool* pool; + }; + static_assert(sizeof(TaskData) <= sizeof(task.raw)); + + new (task.raw.data()) TaskData{ + std::forward(thunk), + counter, + sync_sema, + this + }; + + task.thunk = [](void* ptr) { + auto* data = static_cast(ptr); + data->func(); + if (--(*data->counter) == 0) { + data->pool->notify_sema(data->sema); + } + }; + + task.deleter = [](void* ptr) { + static_cast(ptr)->~TaskData(); + }; + + task.pseudosema = cur_sema_; + q->push(std::move(task)); + } + + wait_sema(sync_sema); +} + } // namespace srb2 extern "C" {