ThreadSchedule 2.2.0
Modern C++ thread management library
Loading...
Searching...
No Matches
task_group.hpp
Go to the documentation of this file.
1#pragma once
2
12
13#include <exception>
14#include <future>
15#include <mutex>
16#include <vector>
17
18namespace threadschedule
19{
20
47template <typename Pool>
49{
50 public:
51 explicit task_group(Pool& pool) : pool_(pool) {}
52
53 task_group(task_group const&) = delete;
54 auto operator=(task_group const&) -> task_group& = delete;
55
57 {
58 try
59 {
60 wait();
61 }
62 catch (...)
63 {
64 }
65 }
66
73 template <typename F>
74 void submit(F&& f)
75 {
76 auto future = pool_.submit(std::forward<F>(f));
77 std::lock_guard<std::mutex> lock(mutex_);
78 futures_.push_back(std::move(future));
79 }
80
87 void wait()
88 {
89 std::vector<std::future<void>> local;
90 {
91 std::lock_guard<std::mutex> lock(mutex_);
92 local.swap(futures_);
93 }
94
95 std::exception_ptr first_error;
96 for (auto& f : local)
97 {
98 try
99 {
100 f.get();
101 }
102 catch (...)
103 {
104 if (!first_error)
105 first_error = std::current_exception();
106 }
107 }
108
109 if (first_error)
110 std::rethrow_exception(first_error);
111 }
112
116 [[nodiscard]] auto pending() const -> size_t
117 {
118 std::lock_guard<std::mutex> lock(mutex_);
119 return futures_.size();
120 }
121
122 private:
123 Pool& pool_;
124 mutable std::mutex mutex_;
125 std::vector<std::future<void>> futures_;
126};
127
128} // namespace threadschedule
auto pending() const -> size_t
Number of pending (not yet waited) tasks.
auto operator=(task_group const &) -> task_group &=delete
void wait()
Block until all submitted tasks complete.
void submit(F &&f)
Submit a void() callable to the group.
task_group(task_group const &)=delete