12#include <boost/optional.hpp>
15#pragma warning(disable:4583)
16#pragma warning(disable:4582)
17#include <boost/variant2/variant.hpp>
20#include <boost/variant2/variant.hpp>
23#include <condition_variable>
32 class SharedException;
60 template <
typename T2>
66 template <
typename ExceptionT>
73 std::condition_variable
_cv;
77 boost::variant2::variant<SharedException, T>
value;
80 std::map<const char *, mapped_type>
_map;
95 :
_exception(
std::make_shared<
std::runtime_error>(
"uninitialized SharedException")) {}
100 const char *
what() const noexcept
override {
116 template <
typename T>
121 std::unique_lock<std::mutex> lock(_mutex);
123 r.should_wait =
true;
125 if (!_cv.wait_for(lock, timeout.
to_chrono(), [&]() { return !r.should_wait; })) {
128 if (r.value.index() == 0) {
131 return boost::variant2::get<T>(std::move(r.value));
135 template <
typename T>
136 template <
typename T2>
138 std::lock_guard<std::mutex> lock(_mutex);
139 for (
auto &pair : _map) {
140 pair.second.should_wait =
false;
141 pair.second.value = value;
146 template <
typename T>
147 template <
typename ExceptionT>
150 SetValue(
SharedException(std::make_shared<ExceptionT>(std::forward<ExceptionT>(e))));
这个类类似于共享未来(shared future)的使用方式,但是它的值可以被设置任意次数的值。 未来设计模式的核心思想是异步调用。 Future接口象征着异步执行任务的结果即执行一个耗时任务完全可以另...
std::map< const char *, mapped_type > _map
void SetException(ExceptionT &&exception)
设置一个异常,这个异常将会被抛给所有正在等待的线程
void SetValue(const T2 &value)
设置值并通知所有等待的线程
boost::optional< T > WaitFor(time_duration timeout)
等待直到下一个值被设置。任意数量的线程可以同时等待。
std::condition_variable _cv
const char * what() const noexcept override
SharedException(std::shared_ptr< std::exception > e)
std::shared_ptr< std::exception > GetException() const
std::shared_ptr< std::exception > _exception
Positive time duration up to milliseconds resolution.
constexpr auto to_chrono() const
static thread_local const char thread_tag
void throw_exception(const std::exception &e)
boost::variant2::variant< SharedException, T > value