LCOV - code coverage report
Current view: top level - src/base - multi_loop.cc (source / functions) Hit Total Coverage
Test: vlink Lines: 88 89 98.9 %
Date: 2026-07-26 14:05:51 Functions: 13 14 92.9 %
Branches: 58 108 53.7 %

           Branch data     Line data    Source code
       1                 :            : /*
       2                 :            :  * Copyright (C) 2026 by Thun Lu. All rights reserved.
       3                 :            :  * Author: Thun Lu <thun.lu@zohomail.cn>
       4                 :            :  * Repo:   https://github.com/thun-res/vlink
       5                 :            :  *  _    __   __      _           __
       6                 :            :  * | |  / /  / /     (_) ____    / /__
       7                 :            :  * | | / /  / /     / / / __ \  / //_/
       8                 :            :  * | |/ /  / /___  / / / / / / / ,<
       9                 :            :  * |___/  /_____/ /_/ /_/ /_/ /_/|_|
      10                 :            :  *
      11                 :            :  * Licensed under the Apache License, Version 2.0 (the "License");
      12                 :            :  * you may not use this file except in compliance with the License.
      13                 :            :  * You may obtain a copy of the License at
      14                 :            :  *
      15                 :            :  *     http://www.apache.org/licenses/LICENSE-2.0
      16                 :            :  *
      17                 :            :  * Unless required by applicable law or agreed to in writing, software
      18                 :            :  * distributed under the License is distributed on an "AS IS" BASIS,
      19                 :            :  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      20                 :            :  * See the License for the specific language governing permissions and
      21                 :            :  * limitations under the License.
      22                 :            :  */
      23                 :            : 
      24                 :            : #include "./base/multi_loop.h"
      25                 :            : 
      26                 :            : #include <atomic>
      27                 :            : #include <chrono>
      28                 :            : #include <memory>
      29                 :            : #include <mutex>
      30                 :            : #include <optional>
      31                 :            : #include <utility>
      32                 :            : 
      33                 :            : #include "./base/condition_variable.h"
      34                 :            : #include "./base/logger.h"
      35                 :            : #include "./base/thread_pool.h"
      36                 :            : 
      37                 :            : namespace vlink {
      38                 :            : 
      39                 :            : // MultiLoopGlobal
      40                 :            : struct MultiLoopGlobal final {
      41                 :            :   std::atomic<int> instance_index{0};
      42                 :            : 
      43                 :         26 :   static MultiLoopGlobal& get() {
      44                 :            :     static MultiLoopGlobal instance;
      45                 :            : 
      46                 :         26 :     return instance;
      47                 :            :   }
      48                 :            : 
      49                 :            :  private:
      50                 :            :   MultiLoopGlobal() = default;
      51                 :            : };
      52                 :            : 
      53                 :            : // MultiLoop::Impl
      54                 :            : struct MultiLoop::Impl final {
      55                 :            :   mutable std::mutex pool_mtx;
      56                 :            :   mutable std::mutex idle_mtx;
      57                 :            :   ConditionVariable idle_cv;
      58                 :            :   std::atomic_size_t pending_tasks{0U};
      59                 :            :   std::optional<ThreadPool> thread_pool;
      60                 :            :   size_t thread_num{0};
      61                 :            : };
      62                 :            : 
      63                 :            : // MultiLoop
      64         [ +  - ]:         21 : MultiLoop::MultiLoop(size_t thread_num) : impl_(std::make_unique<Impl>()) {
      65                 :         21 :   impl_->thread_num = thread_num;
      66                 :            : 
      67   [ +  -  +  - ]:         21 :   set_name("MultiLoop_" +
      68         [ +  - ]:         63 :            std::to_string(MultiLoopGlobal::get().instance_index.fetch_add(1, std::memory_order_relaxed)));
      69                 :         21 : }
      70                 :            : 
      71         [ +  - ]:          5 : MultiLoop::MultiLoop(size_t thread_num, Type type) : MessageLoop(type), impl_(std::make_unique<Impl>()) {
      72                 :          5 :   impl_->thread_num = thread_num;
      73                 :            : 
      74   [ +  -  +  - ]:          5 :   set_name("MultiLoop_" +
      75         [ +  - ]:         15 :            std::to_string(MultiLoopGlobal::get().instance_index.fetch_add(1, std::memory_order_relaxed)));
      76                 :            : 
      77                 :            :   // if VUNLIKELY (type == MultiLoop::kPriorityType) {
      78                 :            :   //   CLOG_F("MultiLoop not support priority type(%s).", get_name().c_str());
      79                 :            :   // }
      80                 :          5 : }
      81                 :            : 
      82                 :         26 : MultiLoop::~MultiLoop() = default;
      83                 :            : 
      84                 :         27 : bool MultiLoop::is_in_same_thread() const {
      85   [ +  -  -  + ]:         27 :   if (MessageLoop::is_in_same_thread()) {
      86                 :            :     return true;  // LCOV_EXCL_LINE GCOVR_EXCL_LINE
      87                 :            :   }
      88                 :            : 
      89         [ +  - ]:         27 :   std::lock_guard lock(impl_->pool_mtx);
      90                 :            : 
      91         [ +  + ]:         27 :   if VUNLIKELY (!impl_->thread_pool) {
      92                 :            :     return false;  // LCOV_EXCL_LINE GCOVR_EXCL_LINE
      93                 :            :   }
      94                 :            : 
      95         [ +  - ]:         25 :   return impl_->thread_pool->is_in_work_thread();
      96                 :         27 : }
      97                 :            : 
      98                 :          6 : bool MultiLoop::wait_for_idle(int ms, bool check) {
      99                 :          6 :   const auto start_time = std::chrono::steady_clock::now();
     100                 :            : 
     101                 :         18 :   auto idle_predicate = [this]() -> bool { return impl_->pending_tasks.load(std::memory_order_acquire) == 0U; };
     102                 :            : 
     103                 :         36 :   auto remaining_ms = [ms, start_time]() -> int {
     104         [ -  + ]:         12 :     if (ms == Timer::kInfinite) {
     105                 :            :       return Timer::kInfinite;  // LCOV_EXCL_LINE GCOVR_EXCL_LINE
     106                 :            :     }
     107                 :            : 
     108                 :            :     const auto elapsed =
     109   [ +  -  +  - ]:         12 :         std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time).count();
     110                 :            : 
     111         [ -  + ]:         12 :     if (elapsed >= ms) {
     112                 :            :       return 0;  // LCOV_EXCL_LINE GCOVR_EXCL_LINE
     113                 :            :     }
     114                 :            : 
     115                 :         12 :     return static_cast<int>(ms - elapsed);
     116                 :          6 :   };
     117                 :            : 
     118                 :          6 :   bool first_check = check;
     119                 :            : 
     120                 :            :   while (true) {
     121         [ +  - ]:          6 :     const int dispatcher_wait_ms = remaining_ms();
     122                 :            : 
     123   [ +  -  -  + ]:          6 :     if (!MessageLoop::wait_for_idle(dispatcher_wait_ms, first_check)) {
     124                 :          6 :       return false;
     125                 :            :     }
     126                 :            : 
     127                 :          6 :     first_check = false;
     128                 :            : 
     129         [ +  - ]:          6 :     std::unique_lock lock(impl_->idle_mtx);
     130                 :            : 
     131         [ -  + ]:          6 :     if (ms == Timer::kInfinite) {
     132                 :            :       impl_->idle_cv.wait(lock, idle_predicate);  // LCOV_EXCL_LINE GCOVR_EXCL_LINE
     133                 :            :     } else {
     134         [ +  - ]:          6 :       const int worker_wait_ms = remaining_ms();
     135                 :            : 
     136         [ -  + ]:          6 :       if (worker_wait_ms <= 0) {
     137                 :            :         return idle_predicate() && MessageLoop::wait_for_idle(0, false);  // LCOV_EXCL_LINE GCOVR_EXCL_LINE
     138                 :            :       }
     139                 :            : 
     140   [ +  -  -  + ]:          6 :       if (!impl_->idle_cv.wait_for(lock, std::chrono::milliseconds(worker_wait_ms),
     141                 :            :                                    idle_predicate)) {  // LCOV_EXCL_LINE GCOVR_EXCL_LINE
     142                 :            :         return false;                                  // LCOV_EXCL_LINE GCOVR_EXCL_LINE
     143                 :            :       }
     144                 :            :     }
     145                 :            : 
     146         [ +  - ]:          6 :     lock.unlock();
     147                 :            : 
     148   [ +  -  +  - ]:          6 :     if (MessageLoop::wait_for_idle(0, false)) {
     149                 :          6 :       return true;
     150                 :            :     }
     151         [ -  + ]:          6 :   }
     152                 :            : }
     153                 :            : 
     154                 :         19 : void MultiLoop::on_begin() {
     155                 :            :   {
     156         [ +  - ]:         19 :     std::lock_guard lock(impl_->pool_mtx);
     157                 :            : 
     158   [ +  -  +  + ]:         19 :     if (get_type() == MultiLoop::kNormalType) {
     159         [ +  - ]:         18 :       impl_->thread_pool.emplace(impl_->thread_num, ThreadPool::kNormalType);
     160   [ +  -  -  + ]:          1 :     } else if (get_type() == MultiLoop::kLockfreeType) {
     161         [ #  # ]:          0 :       impl_->thread_pool.emplace(impl_->thread_num, ThreadPool::kLockfreeType);
     162   [ +  -  +  - ]:          1 :     } else if (get_type() == MultiLoop::kPriorityType) {
     163         [ +  - ]:          1 :       impl_->thread_pool.emplace(impl_->thread_num, ThreadPool::kNormalType);
     164                 :            :     }
     165                 :         19 :   }
     166                 :            : 
     167                 :         19 :   MessageLoop::on_begin();
     168                 :         19 : }
     169                 :            : 
     170                 :         18 : void MultiLoop::on_end() {
     171                 :         18 :   ThreadPool* thread_pool = nullptr;
     172                 :            : 
     173                 :            :   {
     174         [ +  - ]:         18 :     std::lock_guard lock(impl_->pool_mtx);
     175                 :            : 
     176         [ +  - ]:         18 :     if (impl_->thread_pool) {
     177                 :         18 :       thread_pool = &*impl_->thread_pool;
     178                 :            :     }
     179                 :         18 :   }
     180                 :            : 
     181         [ +  - ]:         18 :   if (thread_pool != nullptr) {
     182                 :         18 :     thread_pool->shutdown();
     183                 :            :   }
     184                 :            : 
     185                 :            :   {
     186         [ +  - ]:         18 :     std::lock_guard lock(impl_->pool_mtx);
     187                 :         18 :     impl_->thread_pool.reset();
     188                 :         18 :   }
     189                 :            : 
     190                 :         18 :   MessageLoop::on_end();
     191                 :         18 : }
     192                 :            : 
     193                 :        146 : void MultiLoop::on_task_changed(Callback&& callback, uint32_t start_time) {
     194         [ +  - ]:        146 :   auto task = std::make_shared<Callback>(std::move(callback));
     195                 :            : 
     196                 :        146 :   bool posted = false;
     197                 :            : 
     198                 :            :   {
     199         [ +  - ]:        146 :     std::lock_guard lock(impl_->pool_mtx);
     200                 :            : 
     201         [ +  - ]:        146 :     if VLIKELY (impl_->thread_pool) {
     202                 :        146 :       impl_->pending_tasks.fetch_add(1U, std::memory_order_acq_rel);
     203                 :            : 
     204                 :        146 :       auto release_pending = [](Impl* impl) noexcept {
     205                 :        146 :         bool should_notify = false;
     206                 :            : 
     207                 :            :         {
     208                 :        146 :           std::lock_guard<std::mutex> lock(impl->idle_mtx);
     209                 :        146 :           should_notify = impl->pending_tasks.fetch_sub(1U, std::memory_order_acq_rel) == 1U;
     210                 :        146 :         }
     211                 :            : 
     212         [ +  + ]:        146 :         if (should_notify) {
     213                 :         76 :           impl->idle_cv.notify_all();
     214                 :            :         }
     215                 :        146 :       };
     216                 :            : 
     217                 :        146 :       std::unique_ptr<Impl, decltype(release_pending)> pending_token(impl_.get(), release_pending);
     218                 :            : 
     219   [ +  -  +  - ]:        146 :       posted = impl_->thread_pool->post_task([this, task, pending_token = std::move(pending_token),
     220                 :            :                                               start_time]() mutable {  // LCOV_EXCL_LINE GCOVR_EXCL_LINE
     221         [ +  - ]:        145 :         if VLIKELY (*task) {
     222                 :        145 :           MessageLoop::on_task_changed(std::move(*task), start_time);
     223                 :            :         }
     224                 :            : 
     225                 :            :         (void)pending_token;
     226                 :        145 :       });
     227                 :        146 :     }
     228                 :        146 :   }
     229                 :            : 
     230   [ +  +  +  -  :        146 :   if VUNLIKELY (!posted && *task) {
                   +  + ]
     231                 :            :     MessageLoop::on_task_changed(std::move(*task), start_time);  // LCOV_EXCL_LINE GCOVR_EXCL_LINE
     232                 :            :   }
     233                 :        146 : }
     234                 :            : 
     235                 :            : }  // namespace vlink

Generated by: LCOV version 1.14