LCOV - code coverage report
Current view: top level - source/ps - TaskManager.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 94 96 97.9 %
Date: 2026-12-03 01:19:39 Functions: 16 18 88.9 %

          Line data    Source code
       1             : /* Copyright (C) 2025 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "TaskManager.h"
      21             : 
      22             : #include "lib/debug.h"
      23             : #include "maths/MathUtil.h"
      24             : #include "ps/Profiler2.h"
      25             : #include "ps/Threading.h"
      26             : 
      27             : #include <atomic>
      28             : #include <condition_variable>
      29             : #include <deque>
      30             : #include <functional>
      31             : #include <memory>
      32             : #include <mutex>
      33             : #include <string>
      34             : #include <thread>
      35             : 
      36             : namespace Threading
      37             : {
      38             : 
      39             : namespace
      40             : {
      41             : /**
      42             :  * Minimum number of TaskManager workers.
      43             :  */
      44             : constexpr size_t MIN_WORKERS = 3;
      45             : 
      46             : /**
      47             :  * Maximum number of TaskManager workers.
      48             :  */
      49             : constexpr size_t MAX_WORKERS = 32;
      50             : 
      51           1 : size_t GetDefaultNumberOfWorkers()
      52             : {
      53           2 :     const size_t hardware_concurrency = std::thread::hardware_concurrency();
      54           1 :     return hardware_concurrency ? Clamp(hardware_concurrency - 1, MIN_WORKERS, MAX_WORKERS) : MIN_WORKERS;
      55             : }
      56             : 
      57             : } // anonymous namespace
      58             : 
      59             : using QueueItem = std::function<void()>;
      60             : 
      61             : /**
      62             :  * Light wrapper around std::thread. Ensures Join has been called.
      63             :  */
      64             : class Thread
      65             : {
      66             : public:
      67           3 :     Thread() = default;
      68             :     Thread(const Thread&) = delete;
      69             :     Thread(Thread&&) = delete;
      70             : 
      71             :     template<typename T, void(T::* callable)()>
      72           3 :     void Start(T* object)
      73             :     {
      74           3 :         m_Thread = std::thread(HandleExceptions<DoStart<T, callable>>::Wrapper, object);
      75           3 :     }
      76             :     template<typename T, void(T::* callable)()>
      77             :     static void DoStart(T* object);
      78             : 
      79             : protected:
      80           3 :     ~Thread()
      81             :     {
      82           3 :         ENSURE(!m_Thread.joinable());
      83           3 :     }
      84             : 
      85             :     std::thread m_Thread;
      86             :     std::atomic<bool> m_Kill = false;
      87             : };
      88             : 
      89             : /**
      90             :  * Worker thread: process the taskManager queues until killed.
      91             :  */
      92             : class WorkerThread : public Thread
      93             : {
      94             : public:
      95             :     WorkerThread(TaskManager::Impl& taskManager);
      96             :     ~WorkerThread();
      97             : 
      98             :     /**
      99             :      * Wake the worker.
     100             :      */
     101             :     void Wake();
     102             : 
     103             : protected:
     104             :     void RunUntilDeath();
     105             : 
     106             :     std::mutex m_Mutex;
     107             :     std::condition_variable m_ConditionVariable;
     108             : 
     109             :     TaskManager::Impl& m_TaskManager;
     110             : };
     111             : 
     112             : /**
     113             :  * PImpl-ed implementation of the Task manager.
     114             :  *
     115             :  * The normal priority queue is processed first, the low priority only if there are no higher-priority tasks
     116             :  */
     117             : class TaskManager::Impl
     118             : {
     119             :     friend class TaskManager;
     120             :     friend class WorkerThread;
     121             : public:
     122           3 :     Impl() = default;
     123           1 :     ~Impl()
     124             :     {
     125           1 :         {
     126           1 :             std::lock_guard<std::mutex> lock(m_GlobalMutex);
     127           1 :             ENSURE(m_GlobalQueue.empty());
     128           1 :         }
     129           1 :         {
     130           1 :             std::lock_guard<std::mutex> lock(m_GlobalLowPriorityMutex);
     131           1 :             ENSURE(m_GlobalLowPriorityQueue.empty());
     132           1 :         }
     133           1 :     }
     134             : 
     135             :     /**
     136             :      * 2-phase init to avoid having to think too hard about the order of class members.
     137             :      */
     138             :     void SetupWorkers(size_t numberOfWorkers);
     139             : 
     140             :     /**
     141             :      * Push a task on the global queue.
     142             :      * Takes ownership of @a task.
     143             :      * May be called from any thread.
     144             :      */
     145             :     void PushTask(std::function<void()>&& task, TaskPriority priority);
     146             : 
     147             : protected:
     148             :     void ClearQueue();
     149             : 
     150             :     template<TaskPriority Priority>
     151             :     bool PopTask(std::function<void()>& taskOut);
     152             : 
     153             :     std::atomic<bool> m_HasWork = false;
     154             :     std::atomic<bool> m_HasLowPriorityWork = false;
     155             :     std::mutex m_GlobalMutex;
     156             :     std::mutex m_GlobalLowPriorityMutex;
     157             :     std::deque<QueueItem> m_GlobalQueue;
     158             :     std::deque<QueueItem> m_GlobalLowPriorityQueue;
     159             : 
     160             :     // Ideally this would be a vector, since it does get iterated, but that requires movable types.
     161             :     std::deque<WorkerThread> m_Workers;
     162             : };
     163             : 
     164           2 : TaskManager::TaskManager() : TaskManager(GetDefaultNumberOfWorkers())
     165             : {
     166           1 : }
     167             : 
     168           1 : TaskManager::TaskManager(size_t numberOfWorkers)
     169           1 :     : m{std::make_unique<Impl>()}
     170             : {
     171           1 :     numberOfWorkers = Clamp<size_t>(numberOfWorkers, MIN_WORKERS, MAX_WORKERS);
     172           1 :     m->SetupWorkers(numberOfWorkers);
     173           1 : }
     174             : 
     175           1 : TaskManager::~TaskManager() = default;
     176             : 
     177           1 : void TaskManager::Impl::SetupWorkers(size_t numberOfWorkers)
     178             : {
     179           4 :     for (size_t i = 0; i < numberOfWorkers; ++i)
     180           3 :         m_Workers.emplace_back(*this);
     181           0 : }
     182             : 
     183         210 : size_t TaskManager::GetNumberOfWorkers() const
     184             : {
     185         210 :     return m->m_Workers.size();
     186             : }
     187             : 
     188      100773 : void TaskManager::PushTask(std::function<void()> task, TaskPriority priority)
     189             : {
     190      100773 :     m->PushTask(std::move(task), priority);
     191      100504 : }
     192             : 
     193      100870 : void TaskManager::Impl::PushTask(std::function<void()>&& task, TaskPriority priority)
     194             : {
     195      100870 :     std::mutex& mutex = priority == TaskPriority::NORMAL ? m_GlobalMutex : m_GlobalLowPriorityMutex;
     196      100870 :     std::deque<QueueItem>& queue = priority == TaskPriority::NORMAL ? m_GlobalQueue : m_GlobalLowPriorityQueue;
     197      100870 :     std::atomic<bool>& hasWork = priority == TaskPriority::NORMAL ? m_HasWork : m_HasLowPriorityWork;
     198      100870 :     {
     199      100870 :         std::lock_guard<std::mutex> lock(mutex);
     200      100725 :         queue.emplace_back(std::move(task));
     201      100280 :         hasWork = true;
     202      100698 :     }
     203             : 
     204      401929 :     for (WorkerThread& worker : m_Workers)
     205      301231 :         worker.Wake();
     206      100542 : }
     207             : 
     208             : template<TaskPriority Priority>
     209      134040 : bool TaskManager::Impl::PopTask(std::function<void()>& taskOut)
     210             : {
     211      134040 :     std::mutex& mutex = Priority == TaskPriority::NORMAL ? m_GlobalMutex : m_GlobalLowPriorityMutex;
     212      134040 :     std::deque<QueueItem>& queue = Priority == TaskPriority::NORMAL ? m_GlobalQueue : m_GlobalLowPriorityQueue;
     213      134040 :     std::atomic<bool>& hasWork = Priority == TaskPriority::NORMAL ? m_HasWork : m_HasLowPriorityWork;
     214             : 
     215             :     // Particularly critical section since we're locking the global queue.
     216      134390 :     std::lock_guard<std::mutex> globalLock(mutex);
     217      134390 :     if (!queue.empty())
     218             :     {
     219      100918 :         taskOut = std::move(queue.front());
     220      100918 :         queue.pop_front();
     221      100918 :         hasWork = !queue.empty();
     222      100918 :         return true;
     223             :     }
     224             :     return false;
     225      134330 : }
     226             : 
     227             : // Thread definition
     228             : 
     229           3 : WorkerThread::WorkerThread(TaskManager::Impl& taskManager)
     230           3 :     : m_TaskManager(taskManager)
     231             : {
     232           3 :     Start<WorkerThread, &WorkerThread::RunUntilDeath>(this);
     233           3 : }
     234             : 
     235           3 : WorkerThread::~WorkerThread()
     236             : {
     237           3 :     m_Kill = true;
     238           3 :     m_ConditionVariable.notify_one();
     239           3 :     if (m_Thread.joinable())
     240           3 :         m_Thread.join();
     241           3 : }
     242             : 
     243      301387 : void WorkerThread::Wake()
     244             : {
     245      301387 :     m_ConditionVariable.notify_one();
     246           0 : }
     247             : 
     248           3 : void WorkerThread::RunUntilDeath()
     249             : {
     250             :     // The profiler does better if the names are unique.
     251           3 :     static std::atomic<int> n = 0;
     252           6 :     std::string name = "Task Mgr #" + std::to_string(n++);
     253           3 :     debug_SetThreadName(name.c_str());
     254           3 :     g_Profiler2.RegisterCurrentThread(name);
     255             : 
     256             : 
     257           3 :     std::function<void()> task;
     258           3 :     bool hasTask = false;
     259           3 :     std::unique_lock<std::mutex> lock(m_Mutex, std::defer_lock);
     260           3 :     while (!m_Kill)
     261             :     {
     262      100801 :         lock.lock();
     263      100495 :         m_ConditionVariable.wait(lock, [this](){
     264      101627 :             return m_Kill || m_TaskManager.m_HasWork || m_TaskManager.m_HasLowPriorityWork;
     265             :         });
     266      100628 :         lock.unlock();
     267             : 
     268      100745 :         if (m_Kill)
     269             :             break;
     270             : 
     271             :         // Fetch work from the global queues.
     272      100742 :         hasTask = m_TaskManager.PopTask<TaskPriority::NORMAL>(task);
     273      100915 :         if (!hasTask)
     274       33363 :             hasTask = m_TaskManager.PopTask<TaskPriority::LOW>(task);
     275       33388 :         if (hasTask)
     276      201674 :             task();
     277             :     }
     278           6 : }
     279             : 
     280             : // Defined here - needs access to derived types.
     281             : template<typename T, void(T::* callable)()>
     282           3 : void Thread::DoStart(T* object)
     283             : {
     284           3 :     std::invoke(callable, object);
     285             : }
     286             : 
     287             : } // namespace Threading

Generated by: LCOV version 1.16