1 /* 2 * Generic event loop functionality. 3 * 4 * Copyright (C) 2018, 2023 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 30 31 /* Event loop abstraction. */ 32 33 class Event_loop 34 { 35 protected: 36 /* Thread properties. */ 37 38 int _priority; 39 pthread_t _pthread; 40 41 public: 42 /* Initialise the event loop with a thread priority. */ 43 44 explicit Event_loop(int priority=0x20) 45 : _priority(priority) 46 { 47 } 48 49 /* Static main loop function for event-handling thread. */ 50 51 static void *event_loop(void *data); 52 53 /* Event handler method. */ 54 55 virtual void handle() = 0; 56 57 /* Initiation function. */ 58 59 virtual void start(); 60 }; 61 62 63 64 /* Event loop with handler. */ 65 66 template <class T> 67 class Event_handler_loop : public Event_loop 68 { 69 protected: 70 /* Event type. */ 71 72 typedef T Event_type; 73 74 /* Handler function type. */ 75 76 typedef void (*Event_handler)(Event_type &); 77 78 /* External handler function. */ 79 80 Event_handler _handler; 81 82 public: 83 /* Initialise the event loop with a thread priority. */ 84 85 explicit Event_handler_loop(int priority=0x20) 86 : Event_loop(priority) 87 { 88 } 89 90 /* Attach a handler to the loop. */ 91 92 virtual void attach(Event_handler handler) 93 { 94 _handler = handler; 95 } 96 }; 97 98 /* Event loop with handler and null event type. */ 99 100 template <> 101 class Event_handler_loop<void> : public Event_loop 102 { 103 protected: 104 /* Event type. */ 105 106 typedef void Event_type; 107 108 /* Handler function type. */ 109 110 typedef void (*Event_handler)(); 111 112 /* External handler function. */ 113 114 Event_handler _handler; 115 116 public: 117 /* Initialise the event loop with a thread priority. */ 118 119 explicit Event_handler_loop(int priority=0x20) 120 : Event_loop(priority) 121 { 122 } 123 124 /* Attach a handler to the loop. */ 125 126 virtual void attach(Event_handler handler) 127 { 128 _handler = handler; 129 } 130 }; 131 132 #endif