// eventpp library // Copyright (C) 2018 Wang Qi (wqking) // Github: https://github.com/wqking/eventpp // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef HETEREVENTQUEUE_H_210892536510 #define HETEREVENTQUEUE_H_210892536510 #include "hetereventdispatcher.h" // temp, should move the internal code in eventqueue to separated file #include "eventqueue.h" namespace eventpp { namespace internal_ { template < typename EventType_, typename PrototypeList_, typename Policies_ > class HeterEventQueueBase : public HeterEventDispatcherBase< EventType_, PrototypeList_, Policies_, HeterEventQueueBase < EventType_, PrototypeList_, Policies_ > > { private: using super = HeterEventDispatcherBase< EventType_, PrototypeList_, Policies_, HeterEventQueueBase < EventType_, PrototypeList_, Policies_ > >; using Policies = typename super::Policies; using Threading = typename super::Threading; using ConditionVariable = typename Threading::ConditionVariable; struct QueuedItemBase; using ItemDispatcher = void (*)(const HeterEventQueueBase *, const QueuedItemBase &); struct QueuedItemBase { QueuedItemBase(const int callableIndex, const EventType_ & event, const ItemDispatcher dispatcher) : callableIndex(callableIndex), event(event), dispatcher(dispatcher) { } int callableIndex; EventType_ event; ItemDispatcher dispatcher; }; template struct QueuedItem : public QueuedItemBase { QueuedItem(const int callableIndex, const EventType_ & event, const ItemDispatcher dispatcher, T && arguments) : QueuedItemBase(callableIndex, event, dispatcher), arguments(std::move(arguments)) { } T arguments; }; template using QueuedItemSizer = QueuedItem::type>::type...> >; using BufferedQueuedItem = BufferedUnion::value>; using BufferedItemList = std::list; using PrototypeList = typename super::PrototypeList; using ArgumentPassingMode = typename super::ArgumentPassingMode; public: using Event = typename super::Event; using Handle = typename super::Handle; using Mutex = typename super::Mutex; public: HeterEventQueueBase() : super(), queueListConditionVariable(), queueEmptyCounter(0), queueNotifyCounter(0), queueListMutex(), queueList(), freeListMutex(), freeList() { } HeterEventQueueBase(const HeterEventQueueBase & other) : super(other) { } HeterEventQueueBase(HeterEventQueueBase && other) noexcept : super(std::move(other)) { } HeterEventQueueBase & operator = (const HeterEventQueueBase & other) { super::operator = (other); return *this; } HeterEventQueueBase & operator = (HeterEventQueueBase && other) noexcept { super::operator = (std::move(other)); return *this; } template void enqueue(T && first, Args && ...args) { doEnqueue(std::forward(first), std::forward(args)...); } bool emptyQueue() const { return queueList.empty() && (queueEmptyCounter.load(std::memory_order_acquire) == 0); } void clearEvents() { if(! queueList.empty()) { BufferedItemList tempList; { std::lock_guard queueListLock(queueListMutex); std::swap(queueList, tempList); } if(! tempList.empty()) { for(auto & item : tempList) { item.clear(); } std::lock_guard queueListLock(freeListMutex); freeList.splice(freeList.end(), tempList); } } } bool process() { if(! queueList.empty()) { BufferedItemList tempList; // Use a counter to tell the queue list is not empty during processing // even though queueList is swapped to empty. CounterGuard counterGuard(queueEmptyCounter); { std::lock_guard queueListLock(queueListMutex); std::swap(queueList, tempList); } if(! tempList.empty()) { for(auto & item : tempList) { doDispatchQueuedEvent(item.template get()); item.clear(); } std::lock_guard queueListLock(freeListMutex); freeList.splice(freeList.end(), tempList); return true; } } return false; } bool processOne() { if(! queueList.empty()) { BufferedItemList tempList; // Use a counter to tell the queue list is not empty during processing // even though queueList is swapped to empty. CounterGuard counterGuard(queueEmptyCounter); { std::lock_guard queueListLock(queueListMutex); if(! queueList.empty()) { tempList.splice(tempList.end(), queueList, queueList.begin()); } } if(! tempList.empty()) { auto & item = tempList.front(); doDispatchQueuedEvent(item.template get()); item.clear(); std::lock_guard queueListLock(freeListMutex); freeList.splice(freeList.end(), tempList); return true; } } return false; } template bool processIf(F && func) { if(queueList.empty()) { return false; } using PrototypeInfo = FindPrototypeByCallable; return doProcessIf(std::forward(func)); } void wait() const { std::unique_lock queueListLock(queueListMutex); queueListConditionVariable.wait(queueListLock, [this]() -> bool { return doCanProcess(); }); } template bool waitFor(const std::chrono::duration & duration) const { std::unique_lock queueListLock(queueListMutex); return queueListConditionVariable.wait_for(queueListLock, duration, [this]() -> bool { return doCanProcess(); }); } using super::dispatch; private: bool doCanProcess() const { return ! emptyQueue() && doCanNotifyQueueAvailable(); } bool doCanNotifyQueueAvailable() const { return queueNotifyCounter.load(std::memory_order_acquire) == 0; } void doDispatchQueuedEvent(const QueuedItemBase & item) { item.dispatcher(this, item); } template static void doDispatchItem(const HeterEventQueueBase * self, const QueuedItemBase & baseItem) { const auto & item = static_cast &>(baseItem); self->doDispatchQueuedItem( item, typename MakeIndexSequence::value>::Type() ); } template void doDispatchQueuedItem(T && item, IndexSequence) const { this->directDispatch(item.event, std::get(item.arguments)...); } template auto doProcessIf(F && func) -> typename std::enable_if<(PrototypeInfo::index >= 0), bool>::type { BufferedItemList tempList; BufferedItemList idleList; // Use a counter to tell the queue list is not empty during processing // even though queueList is swapped to empty. CounterGuard counterGuard(queueEmptyCounter); { std::lock_guard queueListLock(queueListMutex); std::swap(queueList, tempList); } if(! tempList.empty()) { for(auto it = tempList.begin(); it != tempList.end(); ) { using ArgsTuple = typename PrototypeInfo::ArgsTuple; auto item = it->template get >(); if(item.callableIndex != PrototypeInfo::index) { ++it; continue; } if(doInvokeFuncWithQueuedEvent( func, item, typename MakeIndexSequence::value>::Type()) ) { doDispatchQueuedEvent(item); it->clear(); auto tempIt = it; ++it; idleList.splice(idleList.end(), tempList, tempIt); } else { ++it; } } if (! tempList.empty()) { std::lock_guard queueListLock(queueListMutex); queueList.splice(queueList.begin(), tempList); } if(! idleList.empty()) { std::lock_guard queueListLock(freeListMutex); freeList.splice(freeList.end(), idleList); return true; } } using NextPrototypeInfo = FindPrototypeByCallableFromIndex; if(doProcessIf(std::forward(func))) { return true; } return false; } template auto doProcessIf(F && /*func*/) -> typename std::enable_if<(PrototypeInfo::index < 0), bool>::type { return false; } template bool doInvokeFuncWithQueuedEvent(F && func, T && item, IndexSequence) const { return doInvokeFuncWithQueuedEventHelper(std::forward(func), std::get(item.arguments)...); } template bool doInvokeFuncWithQueuedEventHelper(F && func, Args && ...args) const { return func(std::forward(args)...); } template auto doEnqueue(T && first, Args && ...args) -> typename std::enable_if::value>::type { using GetEvent = typename SelectGetEvent::value>::Type; using PrototypeInfo = FindPrototypeByArgs; using QueuedItemType = QueuedItem; static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types."); static_assert(std::tuple_size::value == 1 + sizeof...(Args), "Arguments count mismatch."); doEnqueueItem(QueuedItemType( PrototypeInfo::index, GetEvent::getEvent(std::forward(first), args...), &HeterEventQueueBase::doDispatchItem, typename PrototypeInfo::ArgsTuple(std::forward(first), std::forward(args)...) )); if(doCanProcess()) { queueListConditionVariable.notify_one(); } } template auto doEnqueue(T && first, Args && ...args) -> typename std::enable_if::value>::type { using GetEvent = typename SelectGetEvent::value>::Type; using PrototypeInfo = FindPrototypeByArgs; using QueuedItemType = QueuedItem; static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types."); static_assert(std::tuple_size::value == sizeof...(Args), "Arguments count mismatch."); doEnqueueItem(QueuedItemType( PrototypeInfo::index, GetEvent::getEvent(std::forward(first), args...), &HeterEventQueueBase::doDispatchItem, typename PrototypeInfo::ArgsTuple(std::forward(args)...) )); if(doCanProcess()) { queueListConditionVariable.notify_one(); } } template void doEnqueueItem(T && item) { BufferedItemList tempList; if(! freeList.empty()) { { std::lock_guard queueListLock(freeListMutex); if(! freeList.empty()) { tempList.splice(tempList.end(), freeList, freeList.begin()); } } } if(tempList.empty()) { tempList.emplace_back(); } auto it = tempList.begin(); it->set(std::move(item)); std::lock_guard queueListLock(queueListMutex); queueList.splice(queueList.end(), tempList, it); } private: mutable ConditionVariable queueListConditionVariable; typename Threading::template Atomic queueEmptyCounter; typename Threading::template Atomic queueNotifyCounter; mutable Mutex queueListMutex; BufferedItemList queueList; Mutex freeListMutex; BufferedItemList freeList; }; } //namespace internal_ template < typename Event_, typename PrototypeList_, typename Policies_ = DefaultPolicies > class HeterEventQueue : public internal_::InheritMixins< internal_::HeterEventQueueBase, typename internal_::SelectMixins::value >::Type >::Type, public TagEventDispatcher, public TagEventQueue, public TagHeterEventDispatcher, public TagHeterEventQueue { private: using super = typename internal_::InheritMixins< internal_::HeterEventQueueBase, typename internal_::SelectMixins::value >::Type >::Type; public: using super::super; }; } //namespace eventpp #endif