Dispatch Queue
Dispatch Queue / Thread Pool implementation for C++11 with built-in C++20 coroutine support
 
Loading...
Searching...
No Matches
when_any.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <atomic>
4#include <memory>
5
6#include "detail/ranges.hpp"
7#include "task.hpp"
8
9namespace dispatch_queue {
10
11namespace detail {
12
14 template<typename T>
15 void operator()(const task<T>& task) const {
16 if (!result_set->exchange(true, std::memory_order_acq_rel)) {
17 if (auto exception = task.get_exception()) {
18 future->set_exception(exception);
19 }
20 else {
21 future->set_value();
22 }
23 }
24 }
25
26 std::shared_ptr<std::atomic<bool>> result_set = std::make_shared<std::atomic<bool>>(false);
27 std::shared_ptr<detail::task_future<void>> future = detail::task_future<void>::create_pending();
28};
29
30template<typename TaskRange>
31task<void> when_any_internal(const TaskRange& tasks) {
32 auto tasks_size = detail::range_size(tasks);
33 if (tasks_size == 0) {
34 return detail::task_future<void>::create_ready();
35 }
36 else if (tasks_size == 1) {
37 return *detail::range_begin(tasks);
38 }
39
40 when_any_helper helper;
41 for (auto&& task : tasks) {
42 task.then(helper);
43 }
44 return helper.future;
45}
46
47} // end namespace detail
48
55template<typename T>
56task<void> when_any(std::initializer_list<task<T>> tasks) {
57 return detail::when_any_internal(tasks);
58}
59
66template<typename TaskRange>
67task<void> when_any(const TaskRange& tasks) {
68 return detail::when_any_internal(tasks);
69}
70
71#ifdef __cpp_fold_expressions
78 template<typename... Tasks>
79 task<void> when_any(const Tasks&... tasks) {
80 if constexpr (sizeof...(Tasks) == 0) {
81 return detail::task_future<void>::create_ready();
82 }
83 else if constexpr (sizeof...(Tasks) == 1) {
84 return std::get<0>(std::forward_as_tuple(std::forward<Tasks>(tasks)...));
85 }
86 else {
88 (tasks.then(helper), ...);
89 return helper.future;
90 }
91 }
92#endif // __cpp_fold_expressions
93
94} // end namespace dispatch_queue
Definition task.hpp:32
std::exception_ptr get_exception() const
Definition task.hpp:205
auto then(F &&f) const
Definition task.hpp:124
Definition when_all.hpp:12
task< void > when_any_internal(const TaskRange &tasks)
Definition when_any.hpp:31
Definition dispatch_queue.hpp:19
task< void > when_any(std::initializer_list< task< T > > tasks)
Definition when_any.hpp:56
Definition when_any.hpp:13
std::shared_ptr< std::atomic< bool > > result_set
Definition when_any.hpp:26
std::shared_ptr< detail::task_future< void > > future
Definition when_any.hpp:27
void operator()(const task< T > &task) const
Definition when_any.hpp:15