Toolbox snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
Runner.hpp
Go to the documentation of this file.
1// The Reactive C++ Toolbox.
2// Copyright (C) 2013-2019 Swirly Cloud Limited
3// Copyright (C) 2022 Reactive Markets Limited
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17#ifndef TOOLBOX_SYS_RUNNER_HPP
18#define TOOLBOX_SYS_RUNNER_HPP
19
20#include <toolbox/sys/Log.hpp>
23
24namespace toolbox {
25inline namespace sys {
26
27namespace {
28template <typename T>
29// clang-format off
30concept Runnable = requires (T r) {
31 { r.run() } -> std::convertible_to<bool>;
32 r.stop();
33};
34// clang-format on
35} // namespace
36
37template <typename RunnableT>
38 requires Runnable<RunnableT>
39class Runner {
40 public:
42 : r_{r}
43 , thread_{run, std::ref(r), config}
44 {
45 }
47 {
48 r_.stop();
49 thread_.join();
50 }
51
52 // Copy.
53 Runner(const Runner&) = delete;
54 Runner& operator=(const Runner&) = delete;
55
56 // Move.
57 Runner(Runner&&) = delete;
58 Runner& operator=(Runner&&) = delete;
59
60 private:
61 static void run(RunnableT& r, ThreadConfig config)
62 {
64 try {
66 TOOLBOX_NOTICE << "started " << config.name << " thread";
67 // The run() function returns false when the runnable is stopped.
68 while (r.run()) {
69 }
70 } catch (const std::exception& e) {
71 TOOLBOX_CRIT << "exception on " << config.name << " thread: " << e.what();
73 }
74 TOOLBOX_NOTICE << "stopping " << config.name << " thread";
75 }
76
77 RunnableT& r_;
78 std::thread thread_;
79};
80
81} // namespace sys
82} // namespace toolbox
83
84#endif // TOOLBOX_SYS_RUNNER_HPP
#define TOOLBOX_CRIT
Definition Log.hpp:92
#define TOOLBOX_NOTICE
Definition Log.hpp:96
Runner(Runner &&)=delete
Runner(const Runner &)=delete
Runner & operator=(const Runner &)=delete
Runner & operator=(Runner &&)=delete
Runner(RunnableT &r, ThreadConfig config)
Definition Runner.hpp:41
STL namespace.
void set_thread_attrs(const ThreadConfig &config)
Definition Thread.cpp:70
void sig_block_all()
Block all signals.
Definition Signal.cpp:82
constexpr auto bind() noexcept
Definition Slot.hpp:92
ThreadConfig holds the thread attributes.
Definition Thread.hpp:29