blob: 6a0b14a67916b104a73320b81e8ece2eb477f41a [file] [log] [blame]
Rolf Badorekef2bf512019-08-20 11:17:15 +03001/*
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
23using namespace shareddatalayer;
24
25namespace
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
37EventFD::EventFD(Engine& engine):
38 EventFD(System::getSystem(), engine)
39{
40}
41
42EventFD::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
49EventFD::~EventFD()
50{
51}
52
53void 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
63void EventFD::atomicPushBack(const Callback& callback)
64{
65 std::lock_guard<std::mutex> guard(callbacksMutex);
66 callbacks.push_back(callback);
67}
68
69EventFD::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
77void EventFD::handleEvents()
78{
79 uint64_t value;
80 system.read(fd, &value, sizeof(value));
81 executeCallbacks();
82}
83
84void EventFD::executeCallbacks()
85{
86 Callbacks callbacks(atomicPopAll());
87 while (!callbacks.empty())
88 popAndExecuteFirstCallback(callbacks);
89}
90
91void EventFD::popAndExecuteFirstCallback(Callbacks& callbacks)
92{
93 const auto callback(callbacks.front());
94 callbacks.pop_front();
95 execute(callback);
96}