Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
folium-app
GitHub Repository: folium-app/Folium
Path: blob/a-new-beginning/SharedDependencies/Sources/eventbus/AsyncEventBus.cpp
2 views
1
#include <eventbus/AsyncEventBus.h>
2
3
namespace Dexode
4
{
5
6
std::size_t AsyncEventBus::processCommandsAndGetQueuedEventsCount()
7
{
8
std::lock_guard<std::mutex> guard {_eventMutex};
9
while(_commandsQueue.empty() == false)
10
{
11
_commandsQueue
12
.front()(); //This can't add any extra commands, because in this queue we story only listen/unlisten stuff
13
_commandsQueue.pop_front();
14
}
15
//Yeah we want to return events count. So don't have to call getQueueEventCount
16
return _eventQueue.size();
17
}
18
19
int AsyncEventBus::consume(int max)
20
{
21
int consumed = 0;
22
23
std::function<void()> eventCommand;
24
while(processCommandsAndGetQueuedEventsCount() > 0 && consumed < max) //order is important
25
{
26
{
27
std::lock_guard<std::mutex> guard {_eventMutex};
28
eventCommand = std::move(_eventQueue.front());
29
_eventQueue.pop_front();
30
}
31
32
eventCommand();
33
++consumed;
34
}
35
36
return consumed;
37
}
38
39
bool AsyncEventBus::wait()
40
{
41
using namespace std::chrono_literals;
42
std::unique_lock<std::mutex> lock(_waitMutex);
43
_eventWaiting.wait(lock);
44
return not _eventQueue.empty();
45
}
46
bool AsyncEventBus::waitFor(std::chrono::milliseconds timeout)
47
{
48
using namespace std::chrono_literals;
49
std::unique_lock<std::mutex> lock(_waitMutex);
50
_eventWaiting.wait_for(lock, timeout);
51
52
return not _eventQueue.empty();
53
}
54
55
} // namespace Dexode
56
57