xrpld
Loading...
Searching...
No Matches
thread.h
1// Distributed under the Boost Software License, Version 1.0. (See accompanying
2// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
3//
4
5#pragma once
6
7#include <xrpl/beast/unit_test/suite.h>
8
9#include <exception>
10#include <functional>
11#include <string>
12#include <thread>
13#include <utility>
14
15namespace beast::unit_test {
16
20class Thread
21{
22private:
23 Suite* s_ = nullptr;
25
26public:
28 using native_handle_type = std::thread::native_handle_type;
29
30 Thread() = default;
31 Thread(Thread const&) = delete;
32 Thread&
33 operator=(Thread const&) = delete;
34
35 Thread(Thread&& other) : s_(other.s_), t_(std::move(other.t_))
36 {
37 }
38
39 Thread&
41 {
42 s_ = other.s_;
43 t_ = std::move(other.t_);
44 return *this;
45 }
46
47 template <class F, class... Args>
48 explicit Thread(Suite& s, F&& f, Args&&... args) : s_(&s)
49 {
50 std::function<void(void)> b = [f = std::forward<F>(f),
51 ... args = std::forward<Args>(args)]() mutable {
52 std::invoke(f, args...);
53 };
54 t_ = std::thread(&Thread::run, this, std::move(b));
55 }
56
57 [[nodiscard]] bool
58 joinable() const
59 {
60 return t_.joinable();
61 }
62
63 [[nodiscard]] std::thread::id
64 getId() const
65 {
66 return t_.get_id();
67 }
68
69 static unsigned
71 {
73 }
74
75 void
77 {
78 t_.join();
79 s_->propagateAbort();
80 }
81
82 void
84 {
85 t_.detach();
86 }
87
88 void
89 swap(Thread& other)
90 {
91 std::swap(s_, other.s_);
92 std::swap(t_, other.t_);
93 }
94
95private:
96 void
97 run(std::function<void(void)> f)
98 {
99 try
100 {
101 f();
102 }
103 catch (Suite::AbortException const&) // NOLINT(bugprone-empty-catch)
104 {
105 }
106 catch (std::exception const& e)
107 {
108 s_->fail("unhandled exception: " + std::string(e.what()));
109 }
110 catch (...)
111 {
112 s_->fail("unhandled exception");
113 }
114 }
115};
116
117} // namespace beast::unit_test
A testsuite class.
Definition suite.h:52
Replacement for std::thread that handles exceptions in unit tests.
Definition thread.h:21
Thread(Thread const &)=delete
Thread & operator=(Thread const &)=delete
Thread(Suite &s, F &&f, Args &&... args)
Definition thread.h:48
Thread(Thread &&other)
Definition thread.h:35
std::thread::native_handle_type native_handle_type
Definition thread.h:28
void swap(Thread &other)
Definition thread.h:89
static unsigned hardwareConcurrency() noexcept
Definition thread.h:70
std::thread::id getId() const
Definition thread.h:64
std::thread::id id
Definition thread.h:27
Thread & operator=(Thread &&other)
Definition thread.h:40
void run(std::function< void(void)> f)
Definition thread.h:97
bool joinable() const
Definition thread.h:58
T forward(T... args)
T hardware_concurrency(T... args)
T invoke(T... args)
STL namespace.
T swap(T... args)
T what(T... args)