dispenso
A library for task parallelism
 
Loading...
Searching...
No Matches
async_request.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
14#pragma once
15
16#if __cplusplus >= 201703L
17#include <optional>
18#else
19#include <dispenso/detail/op_result.h>
20#endif // C++17
21
22#include <dispenso/platform.h>
23
24namespace dispenso {
25
37template <typename T>
39 public:
40 // A lightweight std::optional-like type with a subset of functionality.
41#if __cplusplus >= 201703L
42 using OpResult = std::optional<T>;
43#else
44 using OpResult = detail::OpResult<T>;
45#endif // C++17
46
52 RequestState state = kNone;
53 state_.compare_exchange_strong(state, kNeedsUpdate, std::memory_order_acq_rel);
54 }
55
61 bool updateRequested() const {
62 return state_.load(std::memory_order_acquire) == kNeedsUpdate;
63 }
64
73 template <typename... Args>
74 bool tryEmplaceUpdate(Args&&... args) {
75 RequestState state = kNeedsUpdate;
76 if (!state_.compare_exchange_strong(state, kUpdating, std::memory_order_acq_rel)) {
77 return false;
78 }
79 obj_.emplace(std::forward<Args>(args)...);
80 state_.store(kReady, std::memory_order_release);
81 return true;
82 }
83
90 OpResult getUpdate() {
91 if (state_.load(std::memory_order_acquire) == kReady) {
92 auto obj = std::move(obj_);
93 state_.store(kNone, std::memory_order_release);
94 return obj;
95 }
96 return {};
97 }
98
99 private:
100 enum RequestState { kNone, kNeedsUpdate, kUpdating, kReady };
101 alignas(kCacheLineSize) std::atomic<RequestState> state_ = {kNone};
102 OpResult obj_;
103};
104
105} // namespace dispenso
bool tryEmplaceUpdate(Args &&... args)
bool updateRequested() const
detail::OpResult< T > OpResult
Definition pipeline.h:29