VLink  2.3.0
A high-performance communication middleware
message_loop.h
Go to the documentation of this file.
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 /**
25  * @file message_loop.h
26  * @brief Single-threaded task dispatcher with three queue backends, timers and scheduling envelopes.
27  *
28  * @details
29  * @c MessageLoop is VLink's serial task executor. It owns a bounded task queue and the timer
30  * registry attached to it; tasks posted from any thread execute in order on the loop's own
31  * thread. Three queue implementations are available; the choice is fixed at construction.
32  *
33  * @par Dispatch mode table
34  *
35  * | Queue type | Backend | Capacity | Properties |
36  * | ----------------- | ------------------------------------ | -------- | --------------------------- |
37  * | @c kNormalType | @c mutex @c + @c std::deque (or pmr) | 10000 | FIFO, lock-based (default) |
38  * | @c kLockfreeType | @c MpmcQueue<Callback> | 10000 | Lock-free MPMC |
39  * | @c kPriorityType | Two pmr priority queues | 10000 | Droppable / protected split |
40  *
41  * Back-pressure on a full queue is selected by @c Strategy: @c kOptimizationStrategy retries
42  * up to ten times with 1 ms sleeps before dropping an eligible task, @c kPopStrategy drops
43  * immediately, and @c kBlockStrategy waits for capacity on lock-based queues or retries indefinitely
44  * on the lock-free queue. Idle dispatch is always condition-variable driven and independent of
45  * @c Strategy. A blocking post issued from the @c run() / @c async_run() thread into its own full
46  * queue is rejected instead of waiting on itself; a thread driving @c spin_once() is not
47  * recognised, so it must not issue such a post.
48  *
49  * @par Lifecycle diagram
50  *
51  * @verbatim
52  * run() / async_run()
53  * +--------+ |
54  * | idle | ----- async_run -----> | spawn thread
55  * +--------+ |
56  * ^ v
57  * | +--------+
58  * | wait_for_quit | active | <-- post_task / exec_task
59  * | (joined) +--------+
60  * | |
61  * | quit() | quit(true)
62  * | v
63  * | +--------+
64  * +------- on_end() -------- | drain | -- pending tasks --> dropped
65  * +--------+
66  * @endverbatim
67  *
68  * @par Priority levels
69  *
70  * | Symbol | Value | Notes |
71  * | ----------------------- | ----- | ------------------------------ |
72  * | @c kNoPriority | 0 | FIFO sentinel |
73  * | @c kLowestPriority | 1 | Lowest real priority |
74  * | @c kTimerPriority | 50 | Reserved for timer callbacks |
75  * | @c kNormalPriority | 100 | Default user-task priority |
76  * | @c kHighestPriority | 65535 | Highest priority |
77  *
78  * @par Example
79  * @code
80  * vlink::MessageLoop loop;
81  * loop.async_run();
82  *
83  * loop.post_task([] { do_work(); });
84  * loop.post_task_with_priority([] { urgent(); }, vlink::MessageLoop::kHighestPriority);
85  *
86  * auto fut = loop.invoke_task([]() -> int { return compute(); });
87  * int result = fut.get(); // wait from a different thread
88  *
89  * loop.quit();
90  * loop.wait_for_quit();
91  * @endcode
92  *
93  * @note Maximum queue depth is @c 10000 (@c kMaxTaskSize) and maximum timer count is @c 100
94  * (@c kMaxTimerSize). Blocking @c .get() on the future returned by @c invoke_task from
95  * inside the loop thread deadlocks; always call it from another thread.
96  */
97 
98 #pragma once
99 
100 #include <atomic>
101 #include <functional>
102 #include <future>
103 #include <limits>
104 #include <memory>
105 #include <mutex>
106 #include <shared_mutex>
107 #include <string>
108 #include <tuple>
109 #include <type_traits>
110 #include <utility>
111 #include <vector>
112 
113 #include "./functional.h"
114 #include "./memory_resource.h"
115 #include "./schedule.h"
116 #include "./task_handle.h"
117 #include "./timer.h"
118 
119 namespace vlink {
120 
121 /**
122  * @class MessageLoop
123  * @brief Serial task dispatcher with selectable queue backend and bounded timer registry.
124  *
125  * @details
126  * Owns a thread that pulls tasks from a bounded queue and fires timer callbacks. Other threads
127  * may post via @c post_task, @c post_task_with_priority, @c invoke_task or @c exec_task from
128  * any context. The class is the building block of @c MultiLoop and the engine target of
129  * @c GraphTask::execute.
130  */
132  public:
133  /**
134  * @brief Callback type for tasks and event handlers.
135  *
136  * @details
137  * Move-only so move-only targets such as @c std::packaged_task or lambdas holding
138  * @c std::unique_ptr can be posted directly without a shared trampoline.
139  */
140  using Callback = MoveFunction<void()>;
141 
142  /**
143  * @brief Internal queue implementation type.
144  */
145  enum Type : uint8_t {
146  kNormalType = 0, ///< Mutex-protected FIFO queue (default).
147  kLockfreeType = 1, ///< Lock-free MPMC queue.
148  kPriorityType = 2, ///< Priority-ordered queue with droppable / protected split.
149  };
150 
151  /**
152  * @brief Back-pressure strategy applied when the bounded queue is at capacity.
153  *
154  * @details
155  * Idle dispatch is unconditionally cv-driven; this enum only affects the push side.
156  */
157  enum Strategy : uint8_t {
158  kOptimizationStrategy = 0, ///< Retry up to ten times, then drop one eligible task and push.
159  kPopStrategy = 1, ///< Drop one eligible task immediately and push.
160  kBlockStrategy = 2, ///< Wait for capacity on lock-based queues; retry on lock-free.
161  };
162 
163  /**
164  * @brief Built-in priority levels for @c kPriorityType loops; higher values dispatch first.
165  */
166  enum Priority : uint16_t {
167  kNoPriority = 0, ///< FIFO sentinel.
168  kLowestPriority = 1, ///< Lowest real priority.
169  kTimerPriority = 50, ///< Reserved for timer callbacks.
170  kNormalPriority = 100, ///< Default user-task priority.
171  kHighestPriority = std::numeric_limits<uint16_t>::max() ///< Highest priority.
172  };
173 
174  /**
175  * @brief Lifetime gate shared with cross-thread observers.
176  *
177  * @details
178  * Callers hold a shared lock on @c mtx while accessing the loop. Destruction first
179  * wakes blocked producers, then takes the exclusive lock and clears @c alive before
180  * releasing resources. During Windows process termination, when all other threads
181  * have already stopped, the destructor performs only the atomic store. Obtain via
182  * @c get_alive_state.
183  */
184  struct AliveState final {
185  std::shared_mutex mtx;
186  std::atomic_bool alive{true};
187  };
188 
189  /**
190  * @brief Constructs a loop with the default @c kNormalType queue.
191  */
193 
194  /**
195  * @brief Constructs a loop with the given queue type.
196  *
197  * @param type Queue implementation.
198  */
199  explicit MessageLoop(Type type);
200 
201  /**
202  * @brief Destructor; requests quit and joins the dispatcher thread if needed.
203  *
204  * @details During Windows process termination it skips cross-thread cleanup and releases its
205  * private state without destroying it because the owning threads have already stopped.
206  *
207  * @warning The loop must not be destroyed from its own dispatcher thread -- that is, from
208  * inside a task, timer callback or event handler it is running. A thread cannot
209  * join itself, so the destructor logs the situation and the join then terminates
210  * the process. Destroy the loop from another thread, or post the deletion
211  * elsewhere.
212  */
213  virtual ~MessageLoop();
214 
215  /**
216  * @brief Sets a human-readable name visible to profiling tools.
217  *
218  * @param name Loop name.
219  */
220  void set_name(const std::string& name);
221 
222  /**
223  * @brief Returns the loop name set via @c set_name.
224  *
225  * @return Reference to the stored name.
226  */
227  [[nodiscard]] const std::string& get_name() const;
228 
229  /**
230  * @brief Returns the queue type this loop was constructed with.
231  *
232  * @return Queue type.
233  */
234  [[nodiscard]] Type get_type() const;
235 
236  /**
237  * @brief Returns the active back-pressure strategy.
238  *
239  * @return Current strategy.
240  */
241  [[nodiscard]] Strategy get_strategy() const;
242 
243  /**
244  * @brief Replaces the back-pressure strategy.
245  *
246  * @details
247  * Wakes producers already waiting under the dispatcher-wide @c kBlockStrategy so they can
248  * observe the new strategy. A producer using an explicit @c TaskOverflowPolicy::kBlock
249  * remains blocked until it is cancelled, queue capacity becomes available, or the loop quits.
250  *
251  * @param strategy New dispatcher-wide strategy.
252  */
253  void set_strategy(Strategy strategy);
254 
255  /**
256  * @brief Registers a callback fired once at loop thread startup.
257  *
258  * @details
259  * Must be registered before @c run / @c async_run; later calls are ignored.
260  *
261  * @param callback Startup handler.
262  */
264 
265  /**
266  * @brief Registers a callback fired once when the loop thread exits.
267  *
268  * @details
269  * Must be registered before @c run / @c async_run; later calls are ignored.
270  *
271  * @param callback Shutdown handler.
272  */
273  void register_end_handler(Callback&& callback);
274 
275  /**
276  * @brief Registers a callback fired every time the queue becomes empty.
277  *
278  * @details
279  * Must be registered before @c run / @c async_run; later calls are ignored.
280  *
281  * @param callback Idle handler.
282  */
283  void register_idle_handler(Callback&& callback);
284 
285  /**
286  * @brief Runs the loop on the calling thread until @c quit is requested.
287  *
288  * @return @c true after a normal exit; @c false when the loop is already running.
289  */
290  bool run();
291 
292  /**
293  * @brief Starts the loop on a new background thread.
294  *
295  * @return @c true when the thread was started; @c false when the loop is already running.
296  */
297  bool async_run();
298 
299  /**
300  * @brief Alias of @c run blocking the calling thread.
301  *
302  * @return Same return value as @c run.
303  */
304  bool spin();
305 
306  /**
307  * @brief Processes one batch of pending tasks and timers on the calling thread.
308  *
309  * @param block When @c true (default) blocks if the queue is empty; when @c false returns immediately.
310  * @return @c true after a normal processing cycle; @c false when quitting or the call came from a
311  * thread that does not own the loop and is unrelated to @c run / @c async_run.
312  */
313  bool spin_once(bool block = true);
314 
315  /**
316  * @brief Requests the loop to exit.
317  *
318  * @details
319  * With @p force @c == @c false the current batch finishes and the loop exits afterwards. With
320  * @p force @c == @c true the in-flight batch is also aborted. Tasks queued after the request
321  * are rejected. Returns @c false when @c quit had already been called (only meaningful when
322  * @p force is @c false).
323  *
324  * @warning This is not a drain. Tasks still sitting in the queue when @c quit is called are
325  * discarded, not executed, regardless of @p force; only the batch already claimed by
326  * the dispatcher runs to completion. A successful @c post_task therefore guarantees
327  * admission, not delivery -- post through @c post_task_handle to observe the
328  * @c TaskExecutionState::kDropped outcome.
329  *
330  * @param force When @c true, also discards the in-flight batch. Default: @c false.
331  * @return @c true when the quit signal was accepted.
332  */
333  bool quit(bool force = false);
334 
335  /**
336  * @brief Waits until the loop has fully exited.
337  *
338  * @param ms Maximum wait in milliseconds; @c Timer::kInfinite means no limit.
339  * @param check When @c true (default) rejects calls from the loop's own thread.
340  * @return @c true if the loop exited before the timeout.
341  */
342  bool wait_for_quit(int ms = Timer::kInfinite, bool check = true);
343 
344  /**
345  * @brief Posts a task for execution on the loop thread.
346  *
347  * @details
348  * Thread-safe. Returns @c false when the loop is quitting or the configured @c Strategy
349  * cannot make room for the new task.
350  *
351  * @param callback Task to post.
352  * @return @c true when the task was enqueued.
353  */
354  bool post_task(Callback&& callback);
355 
356  /**
357  * @brief Tracked variant of @c post_task returning a @c TaskHandle.
358  *
359  * @param callback Task to post.
360  * @param options Optional overflow / drop / cancellation policy.
361  * @return Handle bound to the posted task; valid even when posting was rejected.
362  */
363  [[nodiscard]] TaskHandle post_task_handle(Callback&& callback, const PostTaskOptions& options = {});
364 
365  /**
366  * @brief Posts a task with an explicit priority on a @c kPriorityType loop.
367  *
368  * @details
369  * Higher @p priority values dispatch first. Non-priority loops reject the call and return
370  * @c false.
371  *
372  * @param callback Task to post.
373  * @param priority Dispatch priority in @c [kLowestPriority, @c kHighestPriority].
374  * @return @c true when the task was enqueued.
375  */
376  bool post_task_with_priority(Callback&& callback, uint16_t priority);
377 
378  /**
379  * @brief Tracked variant of @c post_task_with_priority returning a @c TaskHandle.
380  *
381  * @param callback Task to post.
382  * @param priority Dispatch priority.
383  * @param options Optional overflow / drop / cancellation policy.
384  * @return Handle bound to the posted task.
385  */
386  [[nodiscard]] TaskHandle post_task_with_priority_handle(Callback&& callback, uint16_t priority,
387  const PostTaskOptions& options = {});
388 
389  /**
390  * @brief Schedules a @c void-returning callable and returns a chainable @c Schedule::Status.
391  *
392  * @details
393  * @c Schedule::Config carries the delay, priority and timeout fields. The returned status
394  * supports @c on_catch / @c on_schedule_timeout / @c on_execution_timeout chaining. Posting is
395  * deferred until the handle is committed (when the temporary handle is destroyed at the end of
396  * the fluent expression), so every continuation is registered before the task runs. A caller
397  * that stores the handle instead of consuming it inline must call @c Schedule::Status::dispatch()
398  * to post the task and learn whether it was accepted.
399  *
400  * @tparam CallbackT Callable returning @c void.
401  * @param config Scheduling envelope.
402  * @param callback Callable to schedule.
403  * @return Chainable status object.
404  */
405  // NOLINTNEXTLINE(modernize-use-constraints)
406  template <typename CallbackT, typename = std::enable_if_t<!std::is_convertible_v<CallbackT, Schedule::RetCallback>>>
407  Schedule::Status exec_task(const Schedule::Config& config, CallbackT&& callback);
408 
409  /**
410  * @brief Schedules a @c bool-returning callable and returns a chainable @c Schedule::RetStatus.
411  *
412  * @details
413  * @c on_then fires when the callable returns @c true; @c on_else fires when it returns @c false.
414  * Posting is deferred until the handle is committed (destroyed at the end of the fluent
415  * expression), guaranteeing every continuation is registered first; a stored handle must call
416  * @c Schedule::Status::dispatch() to post it.
417  *
418  * @tparam CallbackT Callable returning @c bool.
419  * @param config Scheduling envelope.
420  * @param callback Callable to schedule.
421  * @return Chainable status object.
422  */
423  // NOLINTNEXTLINE(modernize-use-constraints)
424  template <typename CallbackT, typename = std::enable_if_t<std::is_convertible_v<CallbackT, Schedule::RetCallback>>>
425  Schedule::RetStatus exec_task(const Schedule::Config& config, CallbackT&& callback);
426 
427  /**
428  * @brief Wakes the loop thread if it is suspended in its idle wait.
429  *
430  * @details
431  * Concurrent calls coalesce; only the first one after the previous wakeup actually signals.
432  *
433  * @return @c true when a wakeup is pending (newly issued or already in flight).
434  */
435  bool wakeup();
436 
437  /**
438  * @brief Recreates the lock-free queue, clearing all queued tasks and counters.
439  *
440  * @details
441  * Applies only to @c kLockfreeType loops; on other types the call is a no-op. Must be invoked
442  * while the loop is stopped; calls made while it is running are logged and skipped.
443  *
444  * @note The caller must also ensure no other thread is posting concurrently. Producers that
445  * are already inside the queue are waited for, but the reset is logged and skipped if
446  * they do not leave within one second rather than replacing a ring still in use.
447  */
449 
450  /**
451  * @brief Reports whether the loop is currently running.
452  *
453  * @return @c true between a successful start and the corresponding @c quit.
454  */
455  [[nodiscard]] bool is_running() const;
456 
457  /**
458  * @brief Reports whether @c quit has been requested and the loop is winding down.
459  *
460  * @return @c true once @c quit has been observed.
461  */
462  [[nodiscard]] bool is_ready_to_quit() const;
463 
464  /**
465  * @brief Reports whether the loop is currently executing a task.
466  *
467  * @return @c true while a callback is on the call stack inside the loop.
468  */
469  [[nodiscard]] bool is_busy() const;
470 
471  /**
472  * @brief Returns the current pending task count.
473  *
474  * @return Number of tasks waiting in the queue.
475  */
476  [[nodiscard]] size_t get_task_count() const;
477 
478  /**
479  * @brief Waits until the loop has drained its queue and is not executing a task.
480  *
481  * @param ms Maximum wait in milliseconds; @c Timer::kInfinite means no limit.
482  * @param check When @c true (default) rejects calls from the loop's own thread.
483  * @return @c true when the idle condition was reached within @p ms.
484  */
485  virtual bool wait_for_idle(int ms = Timer::kInfinite, bool check = true);
486 
487  /**
488  * @brief Returns the maximum queue depth.
489  *
490  * @return @c kMaxTaskSize (@c 10000) by default.
491  */
492  [[nodiscard]] virtual size_t get_max_task_count() const;
493 
494  /**
495  * @brief Returns the maximum number of timers that can be attached.
496  *
497  * @return @c kMaxTimerSize (@c 100) by default.
498  */
499  [[nodiscard]] virtual size_t get_max_timer_count() const;
500 
501  /**
502  * @brief Returns the maximum allowed task execution time in milliseconds.
503  *
504  * @details
505  * Tasks exceeding this duration trigger @c on_task_timeout. Zero disables the check.
506  *
507  * @return Maximum execution time in milliseconds.
508  */
509  [[nodiscard]] virtual uint32_t get_max_elapsed_time() const;
510 
511  /**
512  * @brief Reports whether the calling thread is owned by this loop.
513  *
514  * @details
515  * Detects callbacks that re-enter the loop synchronously. For @c MultiLoop this also covers
516  * worker threads of the underlying pool.
517  *
518  * @return @c true when called from a thread belonging to this loop.
519  */
520  [[nodiscard]] virtual bool is_in_same_thread() const;
521 
522  /**
523  * @brief Returns the shared lifetime flag used by cross-thread bridges.
524  *
525  * @details
526  * The returned @c AliveState outlives this loop. Adapters that need to post continuations
527  * back to this loop should shared-lock @c mtx, re-check @c alive, and only call back while still
528  * holding the lock.
529  *
530  * @return Shared handle; never null while the loop object is alive.
531  */
532  [[nodiscard]] std::shared_ptr<AliveState> get_alive_state() const;
533 
534  /**
535  * @brief Dispatches a callable to the loop thread and returns a @c std::future for the result.
536  *
537  * @details
538  * Thread-safe. When posting fails the returned future becomes ready with
539  * @c std::future_error / @c broken_promise.
540  *
541  * @warning Do not call @c .get() on the future from the loop's own thread; doing so deadlocks.
542  *
543  * @tparam FunctionT Callable type.
544  * @tparam ArgsT Argument types.
545  * @param function Callable to dispatch.
546  * @param args Arguments copied or moved into owned storage and then moved into the call.
547  * Use @c std::ref to borrow an argument explicitly.
548  * @return Future that becomes ready after the callable completes.
549  */
550  template <class FunctionT, class... ArgsT>
551  [[nodiscard]] auto invoke_task(FunctionT&& function, ArgsT&&... args);
552 
553  /**
554  * @brief Priority variant of @c invoke_task; requires a @c kPriorityType loop.
555  *
556  * @tparam FunctionT Callable type.
557  * @tparam ArgsT Argument types.
558  * @param function Callable to dispatch.
559  * @param priority Dispatch priority.
560  * @param args Arguments copied or moved into owned storage and then moved into the call.
561  * Use @c std::ref to borrow an argument explicitly.
562  * @return Future that becomes ready after the callable completes.
563  */
564  template <class FunctionT, class... ArgsT>
565  [[nodiscard]] auto invoke_task_with_priority(FunctionT&& function, uint16_t priority, ArgsT&&... args);
566 
567  protected:
568  /**
569  * @brief Posts an untracked task with explicit overflow and drop policies.
570  *
571  * @details
572  * Intended for internal data-plane users that need admission control but never observe a
573  * @c TaskHandle after submission. Avoids allocating and synchronising tracked-task state.
574  */
575  bool post_untracked_task(Callback&& callback, TaskOverflowPolicy overflow_policy, TaskDropPolicy drop_policy);
576 
577  /**
578  * @brief Hook invoked once on the loop thread before the first task runs.
579  *
580  * @details
581  * Subclasses override to perform per-thread initialisation.
582  */
583  virtual void on_begin();
584 
585  /**
586  * @brief Hook invoked once on the loop thread after the last task runs.
587  *
588  * @details
589  * Subclasses override to perform per-thread cleanup.
590  */
591  virtual void on_end();
592 
593  /**
594  * @brief Hook invoked on the loop thread each time the queue becomes empty.
595  *
596  * @details
597  * Subclasses override to perform idle bookkeeping.
598  */
599  virtual void on_idle();
600 
601  /**
602  * @brief Dispatches a ready task on the loop thread.
603  *
604  * @details
605  * The default implementation invokes @p callback inline. Subclasses such as @c MultiLoop
606  * override to redirect the call to a worker pool; overrides that do not forward must invoke
607  * @p callback themselves or the task is silently dropped.
608  *
609  * @param callback Task to dispatch.
610  * @param start_time Millisecond @c steady_clock timestamp captured at enqueue time, or @c 0
611  * when elapsed tracking is disabled.
612  */
613  virtual void on_task_changed(Callback&& callback, uint32_t start_time);
614 
615  /**
616  * @brief Hook invoked when a task exceeds @c get_max_elapsed_time().
617  *
618  * @param callback Task that timed out.
619  * @param elapsed_time Actual execution time in milliseconds.
620  */
621  virtual void on_task_timeout(Callback&& callback, uint32_t elapsed_time);
622 
623  private:
624  static uint64_t get_current_nano_time();
625 
626  bool is_current_task_droppable() const;
627 
628  Schedule::Callback make_launcher(const Schedule::Config& config, Schedule::Callback&& wrapper,
629  std::shared_ptr<Schedule::Status::Impl> impl);
630 
631  bool add_timer(Timer* timer);
632 
633  bool remove_timer(Timer* timer);
634 
635  bool push_task(Callback&& callback, uint16_t priority, bool droppable = true,
637  const TaskHandle* submit_handle = nullptr, bool poll_cancellation = false);
638 
639  bool drop_one_normal_task(std::vector<Callback>& dropped);
640 
641  bool drop_one_lockfree_task(std::vector<Callback>& dropped, bool keep_reserved = false);
642 
643  bool drop_one_priority_task(std::vector<Callback>& dropped);
644 
645  bool reserve_lockfree_task();
646 
647  void release_lockfree_task();
648 
649  void push_normal_task(Callback&& callback, bool droppable = true);
650 
651  bool push_lockfree_task(Callback&& callback);
652 
653  void push_priority_task(Callback&& callback, uint16_t priority, bool droppable = true);
654 
655  void do_consume();
656 
657  bool process_normal_task(bool block, bool reuse_queue);
658 
659  bool process_lockfree_task(bool block);
660 
661  bool process_priority_task(bool block);
662 
663  bool process_timer_task(int64_t& next_sleep_time, std::vector<Callback>& dropped_tasks);
664 
665  void drop_pending_tasks();
666 
667  std::unique_lock<std::mutex> lock_timers();
668 
669  friend Timer;
670  friend class MultiLoop;
671  struct Impl;
672  std::unique_ptr<Impl> impl_;
673 
675 };
676 
677 ////////////////////////////////////////////////////////////////
678 /// Details
679 ////////////////////////////////////////////////////////////////
680 
681 template <typename CallbackT, typename>
682 Schedule::Status MessageLoop::exec_task(const Schedule::Config& config, CallbackT&& callback) {
683  Schedule::Callback wrapper_callback;
684 
685  // NOLINTNEXTLINE(bugprone-move-forwarding-reference)
686  auto status = Schedule::process(config, std::move(callback), wrapper_callback);
687 
688  status.launcher_ = make_launcher(config, std::move(wrapper_callback), status.impl_);
689 
690  return status;
691 }
692 
693 template <typename CallbackT, typename>
694 Schedule::RetStatus MessageLoop::exec_task(const Schedule::Config& config, CallbackT&& callback) {
695  Schedule::Callback wrapper_callback;
696 
697  // NOLINTNEXTLINE(bugprone-move-forwarding-reference)
698  auto status = Schedule::process_with_ret(config, std::move(callback), wrapper_callback);
699 
700  status.launcher_ = make_launcher(config, std::move(wrapper_callback), status.impl_);
701 
702  return status;
703 }
704 
705 template <class FunctionT, class... ArgsT>
706 inline auto MessageLoop::invoke_task(FunctionT&& function, ArgsT&&... args) {
707  auto bound = [function = std::forward<FunctionT>(function),
708  args = std::make_tuple(std::forward<ArgsT>(args)...)]() mutable -> decltype(auto) {
709  return std::apply(
710  [&function](auto&&... unpacked_args) -> decltype(auto) {
711  return std::invoke(function, std::forward<decltype(unpacked_args)>(unpacked_args)...);
712  },
713  std::move(args));
714  };
715 
716  using ResultT = std::invoke_result_t<decltype(bound)&>;
717 
718  if constexpr (kIsSupportMoveFunction) {
719  std::packaged_task<ResultT()> task(std::move(bound));
720  auto res = task.get_future();
721 
722  if VUNLIKELY (!post_task([task = std::move(task)]() mutable { task(); })) {
723  }
724 
725  return res;
726  } else {
727  auto task = MemoryResource::make_shared<std::packaged_task<ResultT()>>(std::move(bound));
728  auto res = task->get_future();
729 
730  if VUNLIKELY (!post_task([task]() mutable { (*task)(); })) {
731  task.reset();
732  }
733 
734  return res;
735  }
736 }
737 
738 template <class FunctionT, class... ArgsT>
739 inline auto MessageLoop::invoke_task_with_priority(FunctionT&& function, uint16_t priority, ArgsT&&... args) {
740  auto bound = [function = std::forward<FunctionT>(function),
741  args = std::make_tuple(std::forward<ArgsT>(args)...)]() mutable -> decltype(auto) {
742  return std::apply(
743  [&function](auto&&... unpacked_args) -> decltype(auto) {
744  return std::invoke(function, std::forward<decltype(unpacked_args)>(unpacked_args)...);
745  },
746  std::move(args));
747  };
748 
749  using ResultT = std::invoke_result_t<decltype(bound)&>;
750 
751  if constexpr (kIsSupportMoveFunction) {
752  std::packaged_task<ResultT()> task(std::move(bound));
753  auto res = task.get_future();
754 
755  if VUNLIKELY (!post_task_with_priority([task = std::move(task)]() mutable { task(); }, priority)) {
756  }
757 
758  return res;
759  } else {
760  auto task = MemoryResource::make_shared<std::packaged_task<ResultT()>>(std::move(bound));
761  auto res = task->get_future();
762 
763  if VUNLIKELY (!post_task_with_priority([task]() mutable { (*task)(); }, priority)) {
764  task.reset();
765  }
766 
767  return res;
768  }
769 }
770 
771 inline Schedule::Callback MessageLoop::make_launcher(const Schedule::Config& config, Schedule::Callback&& wrapper,
772  std::shared_ptr<Schedule::Status::Impl> impl) {
773  auto alive_state = get_alive_state();
774 
775  return [this, alive_state = std::move(alive_state), config, impl = std::move(impl),
776  wrapper = std::move(wrapper)]() mutable {
777  std::shared_lock alive_lock(alive_state->mtx);
778 
779  if VUNLIKELY (!alive_state->alive.load(std::memory_order_acquire)) {
780  impl->is_valid.store(false, std::memory_order_relaxed); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
781  return; // LCOV_EXCL_LINE GCOVR_EXCL_LINE
782  }
783 
784  bool post_ret = false;
785 
786  {
787  std::lock_guard lock(impl->mtx);
788  impl->submit_time = std::chrono::steady_clock::now();
789  }
790 
791  if (config.delay_ms > 0) {
792  post_ret = Timer::call_once(this, config.delay_ms, std::move(wrapper), config.priority);
793  } else if (get_type() == kPriorityType && config.priority != kNoPriority) {
794  post_ret = post_task_with_priority(std::move(wrapper), config.priority);
795  } else {
796  post_ret = post_task(std::move(wrapper));
797  }
798 
799  impl->is_valid.store(post_ret, std::memory_order_relaxed);
800  };
801 }
802 
803 } // namespace vlink
Pool-backed type-erased callables: copyable vlink::Function and move-only vlink::MoveFunction.
#define VUNLIKELY(...)
Short alias for VLINK_UNLIKELY.
Definition: macros.h:292
#define VLINK_EXPORT
Definition: macros.h:81
#define VLINK_DISALLOW_COPY_AND_ASSIGN(classname)
Deletes the copy constructor and copy-assignment operator of classname.
Definition: macros.h:174
PMR adapter that lets standard pmr-aware containers allocate through vlink::MemoryPool.
Fluent task-scheduling wrapper used by MessageLoop::exec_task() and family.
Observable handle returned by tracked task-posting APIs of MessageLoop and ThreadPool.
MessageLoop-driven periodic or one-shot timer with priority support.