1 /* 2 * Generic event loop functionality. 3 * 4 * Copyright (C) 2018 Paul Boddie <paul@boddie.org.uk> 5 * 6 * This program is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU General Public License as 8 * published by the Free Software Foundation; either version 2 of 9 * the License, or (at your option) any later version. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, 19 * Boston, MA 02110-1301, USA 20 */ 21 22 #pragma once 23 24 #ifdef __cplusplus 25 26 #include <pthread.h> 27 #include <pthread-l4.h> 28 29 /* Event loop abstraction. */ 30 31 class Event_loop 32 { 33 protected: 34 /* Thread properties. */ 35 36 int _priority; 37 pthread_t _pthread; 38 39 public: 40 /* Initialise the event loop with a thread priority. */ 41 42 explicit Event_loop(int priority=0x20) 43 : _priority(priority) 44 { 45 } 46 47 /* Static main loop function for event-handling thread. */ 48 49 static void *event_loop(void *data); 50 51 /* Event handler method. */ 52 53 virtual void handle() = 0; 54 55 /* Initiation function. */ 56 57 virtual void start(); 58 }; 59 60 61 62 /* Event loop with handler. */ 63 64 template <class T> 65 class Event_handler_loop : public Event_loop 66 { 67 protected: 68 /* Event type. */ 69 70 typedef T Event_type; 71 72 /* Handler function type. */ 73 74 typedef void (*Event_handler)(Event_type &); 75 76 /* External handler function. */ 77 78 Event_handler _handler; 79 80 public: 81 /* Initialise the event loop with a thread priority. */ 82 83 explicit Event_handler_loop(int priority=0x20) 84 : Event_loop(priority) 85 { 86 } 87 88 /* Attach a handler to the loop. */ 89 90 virtual void attach(Event_handler handler) 91 { 92 _handler = handler; 93 } 94 }; 95 96 /* Event loop with handler and null event type. */ 97 98 template <> 99 class Event_handler_loop<void> : public Event_loop 100 { 101 protected: 102 /* Event type. */ 103 104 typedef void Event_type; 105 106 /* Handler function type. */ 107 108 typedef void (*Event_handler)(); 109 110 /* External handler function. */ 111 112 Event_handler _handler; 113 114 public: 115 /* Initialise the event loop with a thread priority. */ 116 117 explicit Event_handler_loop(int priority=0x20) 118 : Event_loop(priority) 119 { 120 } 121 122 /* Attach a handler to the loop. */ 123 124 virtual void attach(Event_handler handler) 125 { 126 _handler = handler; 127 } 128 }; 129 130 #endif