Thread System 0.3.1
High-performance C++20 thread pool with work stealing and DAG scheduling
Loading...
Searching...
No Matches
future_job.h
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2024, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
5#pragma once
6
17
18#include <functional>
19#include <future>
20#include <memory>
21#include <type_traits>
22
23namespace kcenon::thread {
24
44template<typename R>
45class future_job : public job {
46public:
56 template<typename F,
57 typename = std::enable_if_t<std::is_invocable_r_v<R, F>>>
58 explicit future_job(F&& callable, const std::string& name = "future_job")
59 : job(name)
60 , callable_(std::forward<F>(callable))
61 , promise_(std::make_shared<std::promise<R>>())
62 {}
63
72 [[nodiscard]] auto get_future() -> std::future<R> {
73 return promise_->get_future();
74 }
75
76protected:
87 [[nodiscard]] auto do_work() -> common::VoidResult override {
88 // Check for cancellation before starting
90 promise_->set_exception(
91 std::make_exception_ptr(
92 std::runtime_error("Job cancelled before execution")
93 )
94 );
96 }
97
98 try {
99 if constexpr (std::is_void_v<R>) {
100 callable_();
101 promise_->set_value();
102 } else {
103 promise_->set_value(callable_());
104 }
105 } catch (...) {
106 promise_->set_exception(std::current_exception());
107 return make_error_result(
109 "Exception thrown during job execution"
110 );
111 }
112
113 return common::ok();
114 }
115
116private:
117 std::function<R()> callable_;
118 std::shared_ptr<std::promise<R>> promise_;
119};
120
121} // namespace kcenon::thread
bool is_cancelled() const
Checks if the token has been canceled.
A job that wraps a callable and provides a future for its result.
Definition future_job.h:45
auto get_future() -> std::future< R >
Get the future associated with this job.
Definition future_job.h:72
std::shared_ptr< std::promise< R > > promise_
Definition future_job.h:118
future_job(F &&callable, const std::string &name="future_job")
Constructs a future_job from a callable.
Definition future_job.h:58
std::function< R()> callable_
Definition future_job.h:117
auto do_work() -> common::VoidResult override
Executes the callable and sets the promise value.
Definition future_job.h:87
Represents a unit of work (task) to be executed, typically by a job queue.
Definition job.h:136
cancellation_token cancellation_token_
The cancellation token associated with this job.
Definition job.h:504
Error codes and utilities for the thread system.
Base job class for schedulable work units in the thread system.
Core threading foundation of the thread system library.
Definition thread_impl.h:17
common::VoidResult make_error_result(error_code code, const std::string &message="")
Create a common::VoidResult error from a thread::error_code.
STL namespace.