opynsim
Unofficial C++ Documentation
Loading...
Searching...
No Matches
thread.h
Go to the documentation of this file.
1#pragma once
2
4
5#include <version> // __cpp_lib_jthread
6
7#ifdef __cpp_lib_jthread
8 #include <thread>
9#else
10 #include <concepts>
11 #include <thread>
12 #include <utility>
13#endif
14
15namespace osc::cpp20
16{
17#ifdef __cpp_lib_jthread
18 using jthread = std::jthread;
19#else
20 // C++20: std::jthread
21 class jthread final {
22 public:
23 // initializes a new thread object which does not represent a thread
24 jthread() = default;
25
26 // initializes a new thread object and associates it with a thread of execution. The
27 // new thread of execution immediately starts executing
28 template<typename Function, typename... Args>
29 requires std::invocable<Function, stop_token, Args&&...>
31 stop_source_{},
32 thread_{std::forward<Function>(f), stop_source_.get_token(), std::forward<Args>(args)...}
33 {}
34
35 // threads are non-copyable
36 jthread(jthread const&) = delete;
37 jthread& operator=(jthread const&) = delete;
38
39 // threads are moveable: the moved-from value is a non-joinable thread that
40 // does not represent a thread
42
44 {
45 if (joinable()) {
46 stop_source_.request_stop();
47 thread_.join();
48 }
49 std::swap(stop_source_, other.stop_source_);
50 std::swap(thread_, other.thread_);
51 return *this;
52 }
53
54 // jthreads (or "joining threads") cancel + join on destruction
56 {
57 if (joinable()) {
58 stop_source_.request_stop();
59 thread_.join();
60 }
61 }
62
64 {
65 return thread_.joinable();
66 }
67
69 {
70 return stop_source_.request_stop();
71 }
72
73 void join()
74 {
75 return thread_.join();
76 }
77
78 private:
79 stop_source stop_source_;
80 std::thread thread_;
81 };
82#endif
83}
Definition thread.h:21
jthread(Function &&f, Args &&... args)
Definition thread.h:30
jthread & operator=(jthread const &)=delete
jthread(jthread const &)=delete
~jthread() noexcept
Definition thread.h:55
bool joinable() const noexcept
Definition thread.h:63
jthread(jthread &&) noexcept=default
bool request_stop() noexcept
Definition thread.h:68
void join()
Definition thread.h:73
Definition stop_token.h:40
bool request_stop() noexcept
Definition stop_token.h:49
Definition stop_token.h:19
Definition stop_token.h:14
constexpr U to(T &&value)
Definition conversion.h:56