Project SkyFire Core
SkyFire 5.4.8 server core API documentation
Loading...
Searching...
No Matches
Future.h
Go to the documentation of this file.
1/*
2* This file is part of Project SkyFire https://www.projectskyfire.org.
3* See LICENSE.md file for Copyright information
4*/
5
6#ifndef SKYFIRE_FUTURE_H
7#define SKYFIRE_FUTURE_H
8
9#include <chrono>
10#include <future>
11#include <memory>
12#include <mutex>
13
14namespace Skyfire
15{
16 template <class T>
17 class Future
18 {
19 public:
20 Future() : _state(std::make_shared<State>()) { }
21
22 void set(T value)
23 {
24 std::lock_guard<std::mutex> lock(_state->mutex);
25 if (_state->completed)
26 return;
27
28 _state->promise.set_value(value);
29 _state->completed = true;
30 }
31
32 bool ready() const
33 {
34 return _state->future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
35 }
36
37 void get(T& value) const
38 {
39 value = _state->future.get();
40 }
41
42 void cancel()
43 {
44 _state = std::make_shared<State>();
45 }
46
47 private:
48 struct State
49 {
50 State() : future(promise.get_future().share()), completed(false) { }
51
52 std::promise<T> promise;
53 std::shared_future<T> future;
55 std::mutex mutex;
56 };
57
58 std::shared_ptr<State> _state;
59 };
60}
61
62#endif
void cancel()
Definition Future.h:42
void get(T &value) const
Definition Future.h:37
bool ready() const
Definition Future.h:32
std::shared_ptr< State > _state
Definition Future.h:58
void set(T value)
Definition Future.h:22
std::shared_future< T > future
Definition Future.h:53
std::mutex mutex
Definition Future.h:55
std::promise< T > promise
Definition Future.h:52