uvco 0.1
Loading...
Searching...
No Matches
async_work.h
Go to the documentation of this file.
1// uvco (c) 2024 Lewin Bormann. See LICENSE for specific terms.
2
3#include <exception>
4#include <functional>
5#include <utility>
6#include <uv.h>
7
8#include "uvco/loop/loop.h"
10
11#include <optional>
12#include <uv/unix.h>
13#include <variant>
14
15namespace uvco {
16
19
21Promise<void> innerSubmitWork(const Loop &loop, std::function<void()> work);
22
25template <typename R>
26 requires std::is_void_v<R> || std::is_move_constructible_v<R>
27Promise<R> submitWork(const Loop &loop, std::function<R()> work) {
28 std::optional<std::variant<R, std::exception_ptr>> result;
29 // Erase return type and use generic submitWork().
30 std::function<void()> agnosticWork = [&result, work]() {
31 try {
32 result = work();
33 } catch (...) {
34 result = std::current_exception();
35 }
36 };
37 co_await innerSubmitWork(loop, agnosticWork);
38 BOOST_ASSERT(result.has_value());
39 if (result->index() == 1) {
40 std::rethrow_exception(std::get<std::exception_ptr>(*result));
41 }
42 co_return std::get<R>(std::move(*result));
43}
44
45template <>
46Promise<void> submitWork(const Loop &loop, std::function<void()> work);
47
53template <typename T> class ThreadLocalKey {
54public:
56 ThreadLocalKey(const ThreadLocalKey &) = default;
60 ~ThreadLocalKey() = default;
61
64 void del() {
65 auto *value = uv_key_get(&key_);
66 if (value != nullptr) {
67 delete static_cast<T *>(value);
68 uv_key_set(&key_, nullptr);
69 }
70 }
71
74 auto *value = uv_key_get(&key_);
75 if (value == nullptr) {
76 value = new T{};
78 }
79 return *static_cast<T *>(value);
80 }
81
83 T &get() { return *static_cast<T *>(uv_key_get(&key_)); }
84
86 void set(T &&value) { getOrDefault() = std::move(value); }
87
89 void setCopy(const T &value) { getOrDefault() = value; }
90
91private:
93};
94
96
97} // namespace uvco
Definition loop.h:26
Definition promise.h:76
Definition async_work.h:53
ThreadLocalKey(ThreadLocalKey &&)=default
void del()
Definition async_work.h:64
ThreadLocalKey & operator=(const ThreadLocalKey &)=default
ThreadLocalKey & operator=(ThreadLocalKey &&)=default
~ThreadLocalKey()=default
ThreadLocalKey()
Definition async_work.h:55
ThreadLocalKey(const ThreadLocalKey &)=default
T & getOrDefault()
Get the stored value, or create a new one if none exists.
Definition async_work.h:73
void setCopy(const T &value)
Set the stored value.
Definition async_work.h:89
uv_key_t key_
Definition async_work.h:92
void set(T &&value)
Set the stored value.
Definition async_work.h:86
T & get()
Get the stored value. If none exists, this will crash.
Definition async_work.h:83
Promise< void > innerSubmitWork(const Loop &loop, std::function< void()> work)
Do not use; instead, use submitWork<void>().
Definition async_work.cc:87
Promise< void > submitWork(const Loop &loop, std::function< void()> work)
Definition async_work.cc:96
Definition async_work.cc:17