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 <functional>
10#include <thread>
11#include <utility>
12
13namespace beast::unit_test {
14
16class Thread
17{
18private:
19 Suite* s_ = nullptr;
21
22public:
24 using native_handle_type = std::thread::native_handle_type;
25
26 Thread() = default;
27 Thread(Thread const&) = delete;
28 Thread&
29 operator=(Thread const&) = delete;
30
31 Thread(Thread&& other) : s_(other.s_), t_(std::move(other.t_))
32 {
33 }
34
35 Thread&
37 {
38 s_ = other.s_;
39 t_ = std::move(other.t_);
40 return *this;
41 }
42
43 template <class F, class... Args>
44 explicit Thread(Suite& s, F&& f, Args&&... args) : s_(&s)
45 {
46 std::function<void(void)> b = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
47 t_ = std::thread(&Thread::run, this, std::move(b));
48 }
49
50 [[nodiscard]] bool
51 joinable() const
52 {
53 return t_.joinable();
54 }
55
56 [[nodiscard]] std::thread::id
57 getId() const
58 {
59 return t_.get_id();
60 }
61
62 static unsigned
64 {
66 }
67
68 void
70 {
71 t_.join();
72 s_->propagateAbort();
73 }
74
75 void
77 {
78 t_.detach();
79 }
80
81 void
82 swap(Thread& other)
83 {
84 std::swap(s_, other.s_);
85 std::swap(t_, other.t_);
86 }
87
88private:
89 void
90 run(std::function<void(void)> f)
91 {
92 try
93 {
94 f();
95 }
96 catch (Suite::AbortException const&) // NOLINT(bugprone-empty-catch)
97 {
98 }
99 catch (std::exception const& e)
100 {
101 s_->fail("unhandled exception: " + std::string(e.what()));
102 }
103 catch (...)
104 {
105 s_->fail("unhandled exception");
106 }
107 }
108};
109
110} // namespace beast::unit_test
T bind(T... args)
A testsuite class.
Definition suite.h:50
Replacement for std::thread that handles exceptions in unit tests.
Definition thread.h:17
Thread(Thread const &)=delete
Thread & operator=(Thread const &)=delete
Thread(Suite &s, F &&f, Args &&... args)
Definition thread.h:44
Thread(Thread &&other)
Definition thread.h:31
std::thread::native_handle_type native_handle_type
Definition thread.h:24
void swap(Thread &other)
Definition thread.h:82
static unsigned hardwareConcurrency() noexcept
Definition thread.h:63
std::thread::id getId() const
Definition thread.h:57
std::thread::id id
Definition thread.h:23
Thread & operator=(Thread &&other)
Definition thread.h:36
void run(std::function< void(void)> f)
Definition thread.h:90
bool joinable() const
Definition thread.h:51
T forward(T... args)
T hardware_concurrency(T... args)
STL namespace.
T swap(T... args)
T what(T... args)