// Matrix Construct // // Copyright (C) Matrix Construct Developers, Authors & Contributors // Copyright (C) 2016-2018 Jason Volk // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice is present in all copies. The // full license for this software is available in the LICENSE file. #pragma once #define HAVE_IRCD_CTX_PARALLEL_H namespace ircd::ctx { template class parallel; } template struct ircd::ctx::parallel { using closure = std::function; pool *p {nullptr}; vector_view a; closure c; dock d; std::exception_ptr eptr; ushort snd {0}; ushort rcv {0}; bool done() const; bool avail() const; void wait_done(); void wait_avail(); void rethrow_any_exception(); void receiver() noexcept; void sender() noexcept; public: size_t nextpos() const; void operator()(); void operator()(const arg &a); parallel(pool &, const vector_view &, closure); parallel(parallel &&) = delete; parallel(const parallel &) = delete; ~parallel() noexcept; }; template ircd::ctx::parallel::parallel(pool &p, const vector_view &a, closure c) :p{&p} ,a{a} ,c{std::move(c)} { p.min(this->a.size()); } template ircd::ctx::parallel::~parallel() noexcept { const uninterruptible::nothrow ui; wait_done(); } template void ircd::ctx::parallel::operator()(const arg &a) { rethrow_any_exception(); assert(avail()); this->a.at(nextpos()) = a; sender(); wait_avail(); } template void ircd::ctx::parallel::operator()() { rethrow_any_exception(); assert(avail()); sender(); wait_avail(); } template size_t ircd::ctx::parallel::nextpos() const { return snd % a.size(); } template void ircd::ctx::parallel::sender() noexcept { auto &p(*this->p); auto func { std::bind(¶llel::receiver, this) }; ++snd; assert(snd > rcv); if(likely(p.size())) p(std::move(func)); else func(); } template void ircd::ctx::parallel::receiver() noexcept { assert(snd > rcv); const auto pos { rcv % this->a.size() }; if(!this->eptr) try { c(this->a.at(pos)); } catch(...) { this->eptr = std::current_exception(); } ++rcv; d.notify_one(); assert(snd >= rcv); } template void ircd::ctx::parallel::rethrow_any_exception() { if(likely(!this->eptr)) return; wait_done(); const auto eptr(this->eptr); this->eptr = {}; std::rethrow_exception(eptr); } template void ircd::ctx::parallel::wait_avail() { d.wait([this] { return avail(); }); } template void ircd::ctx::parallel::wait_done() { d.wait([this] { return done(); }); } template bool ircd::ctx::parallel::avail() const { assert(snd >= rcv); assert(snd - rcv <= ssize_t(a.size())); return snd - rcv < ssize_t(a.size()); } template bool ircd::ctx::parallel::done() const { assert(snd >= rcv); assert(snd - rcv <= ssize_t(a.size())); return snd - rcv == 0; }