dispenso 1.4.1
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
15#pragma once
16
17#if __cplusplus >= 201703L
18#include <optional>
19#else
20#include <dispenso/detail/op_result.h>
21#endif // C++17
22
23#include <dispenso/platform.h>
24
25namespace dispenso {
26
38template <typename T>
40 public:
41 // A lightweight std::optional-like type with a subset of functionality.
42#if __cplusplus >= 201703L
43 using OpResult = std::optional<T>;
44#else
45 using OpResult = detail::OpResult<T>;
46#endif // C++17
47
53 RequestState state = kNone;
54 state_.compare_exchange_strong(state, kNeedsUpdate, std::memory_order_acq_rel);
55 }
56
62 bool updateRequested() const {
63 return state_.load(std::memory_order_acquire) == kNeedsUpdate;
64 }
65
74 template <typename... Args>
75 bool tryEmplaceUpdate(Args&&... args) {
76 RequestState state = kNeedsUpdate;
77 if (!state_.compare_exchange_strong(state, kUpdating, std::memory_order_acq_rel)) {
78 return false;
79 }
80 obj_.emplace(std::forward<Args>(args)...);
81 state_.store(kReady, std::memory_order_release);
82 return true;
83 }
84
91 OpResult getUpdate() {
92 if (state_.load(std::memory_order_acquire) == kReady) {
93 auto obj = std::move(obj_);
94 state_.store(kNone, std::memory_order_release);
95 return obj;
96 }
97 return {};
98 }
99
100 private:
101 enum RequestState { kNone, kNeedsUpdate, kUpdating, kReady };
102 alignas(kCacheLineSize) std::atomic<RequestState> state_ = {kNone};
103 OpResult obj_;
104};
105
106} // namespace dispenso
bool tryEmplaceUpdate(Args &&... args)
bool updateRequested() const