From 3ee9761b73aff34c7f30ee44b8aac276d413cc21 Mon Sep 17 00:00:00 2001 From: Karen Arutyunov Date: Wed, 14 Oct 2020 16:15:41 +0300 Subject: Add builtin::timed_wait(), builtin::try_wait(), and pseudo_builtin() --- libbutl/builtin.ixx | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 libbutl/builtin.ixx (limited to 'libbutl/builtin.ixx') diff --git a/libbutl/builtin.ixx b/libbutl/builtin.ixx new file mode 100644 index 0000000..0356f8b --- /dev/null +++ b/libbutl/builtin.ixx @@ -0,0 +1,78 @@ +// file : libbutl/builtin.ixx -*- C++ -*- +// license : MIT; see accompanying LICENSE file + +namespace butl +{ + // builtin + // + // Implement timed_wait() function templates in terms of their milliseconds + // specialization. + // + template <> + LIBBUTL_SYMEXPORT optional builtin:: + timed_wait (const std::chrono::milliseconds&); + + template + inline optional builtin:: + timed_wait (const std::chrono::duration& d) + { + using namespace std::chrono; + return timed_wait (duration_cast (d)); + } + + inline optional builtin:: + try_wait () + { + if (state_ != nullptr) + { + std::unique_lock l (state_->mutex); + + if (!state_->finished) + return nullopt; + } + + return result_; + } + + // builtin_map + // + inline const builtin_info* builtin_map:: + find (const std::string& n) const + { + auto i (base::find (n)); + return i != end () ? &i->second : nullptr; + } + + // builtin::async_state + // + template + inline builtin::async_state:: + async_state (F f) + : thread ([f = std::move (f), this] () mutable noexcept + { + f (); + + { + std::unique_lock l (this->mutex); + finished = true; + } + + condv.notify_all (); + }) + { + } + + template + inline builtin + pseudo_builtin (std::uint8_t& r, F f) + { + std::unique_ptr s ( + new builtin::async_state ( + [f = std::move (f), &r] () mutable noexcept + { + r = f (); + })); + + return builtin (r, move (s)); + } +} -- cgit v1.1