IOEventLoop.h revision 825e56be3a1c5310969aaa3e10a7cd1f63455189
1/*
2 * Copyright (C) 2016 The Android Open Source Project
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#ifndef SIMPLE_PERF_IOEVENT_LOOP_H_
18#define SIMPLE_PERF_IOEVENT_LOOP_H_
19
20#include <time.h>
21
22#include <functional>
23#include <memory>
24#include <vector>
25
26struct IOEvent;
27typedef IOEvent* IOEventRef;
28struct event_base;
29
30// IOEventLoop is a class wrapper of libevent, it monitors events happened,
31// and calls the corresponding callbacks. Possible events are: file ready to
32// read, file ready to write, signal happens, periodic timer timeout.
33class IOEventLoop {
34 public:
35  IOEventLoop();
36  ~IOEventLoop();
37
38  // Register a read Event, so [callback] is called when [fd] can be read
39  // without blocking. If registered successfully, return the reference
40  // to control the Event, otherwise return nullptr.
41  IOEventRef AddReadEvent(int fd, const std::function<bool()>& callback);
42
43  // Register a signal Event, so [callback] is called each time signal [sig]
44  // happens.
45  bool AddSignalEvent(int sig, const std::function<bool()>& callback);
46
47  // Register a vector of signal Events.
48  bool AddSignalEvents(std::vector<int> sigs,
49                       const std::function<bool()>& callback);
50
51  // Register a periodic Event, so [callback] is called periodically every
52  // [duration].
53  bool AddPeriodicEvent(timeval duration,
54                        const std::function<bool()>& callback);
55
56  // Run a loop polling for Events. It only exits when ExitLoop() is called
57  // in a callback function of registered Events.
58  bool RunLoop();
59
60  // Exit the loop started by RunLoop().
61  bool ExitLoop();
62
63  // Unregister an Event.
64  static bool DelEvent(IOEventRef ref);
65
66 private:
67  bool EnsureInit();
68  IOEventRef AddEvent(int fd_or_sig, short events, timeval* timeout,
69                      const std::function<bool()>& callback);
70  static void EventCallbackFn(int, short, void*);
71
72  event_base* ebase_;
73  std::vector<std::unique_ptr<IOEvent>> events_;
74  bool has_error_;
75};
76
77#endif  // SIMPLE_PERF_IOEVENT_LOOP_H_
78