Add first version
[ric-plt/sdl.git] / src / eventfd.cpp
1 /*
2    Copyright (c) 2018-2019 Nokia.
3
4    Licensed under the Apache License, Version 2.0 (the "License");
5    you may not use this file except in compliance with the License.
6    You may obtain a copy of the License at
7
8        http://www.apache.org/licenses/LICENSE-2.0
9
10    Unless required by applicable law or agreed to in writing, software
11    distributed under the License is distributed on an "AS IS" BASIS,
12    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13    See the License for the specific language governing permissions and
14    limitations under the License.
15 */
16
17 #include "private/eventfd.hpp"
18 #include <sys/eventfd.h>
19 #include "private/abort.hpp"
20 #include "private/engine.hpp"
21 #include "private/system.hpp"
22
23 using namespace shareddatalayer;
24
25 namespace
26 {
27     /*
28      * Simple wrapper for executing the given callback without expecting
29      * exceptions. If callback throws, we'll crash.
30      */
31     void execute(const EventFD::Callback& callback) noexcept
32     {
33         callback();
34     }
35 }
36
37 EventFD::EventFD(Engine& engine):
38     EventFD(System::getSystem(), engine)
39 {
40 }
41
42 EventFD::EventFD(System& system, Engine& engine):
43     system(system),
44     fd(system, system.eventfd(0U, EFD_CLOEXEC | EFD_NONBLOCK))
45 {
46     engine.addMonitoredFD(fd, Engine::EVENT_IN, std::bind(&EventFD::handleEvents, this));
47 }
48
49 EventFD::~EventFD()
50 {
51 }
52
53 void EventFD::post(const Callback& callback)
54 {
55     if (!callback)
56         SHAREDDATALAYER_ABORT("A null callback was provided");
57
58     atomicPushBack(callback);
59     static const uint64_t value(1U);
60     system.write(fd, &value, sizeof(value));
61 }
62
63 void EventFD::atomicPushBack(const Callback& callback)
64 {
65     std::lock_guard<std::mutex> guard(callbacksMutex);
66     callbacks.push_back(callback);
67 }
68
69 EventFD::Callbacks EventFD::atomicPopAll()
70 {
71     std::lock_guard<std::mutex> guard(callbacksMutex);
72     Callbacks extractedCallbacks;
73     std::swap(callbacks, extractedCallbacks);
74     return extractedCallbacks;
75 }
76
77 void EventFD::handleEvents()
78 {
79     uint64_t value;
80     system.read(fd, &value, sizeof(value));
81     executeCallbacks();
82 }
83
84 void EventFD::executeCallbacks()
85 {
86     Callbacks callbacks(atomicPopAll());
87     while (!callbacks.empty())
88         popAndExecuteFirstCallback(callbacks);
89 }
90
91 void EventFD::popAndExecuteFirstCallback(Callbacks& callbacks)
92 {
93     const auto callback(callbacks.front());
94     callbacks.pop_front();
95     execute(callback);
96 }