8226d465e366cda7bd0d335b58fa4926c9bac528
[monky] / src / timed_thread.c
1 /* $Id$ */
2
3 /* timed_thread.c: Abstraction layer for timed threads
4  *
5  * Copyright (C) 2006-2007 Philip Kovacs pkovacs@users.sourceforge.net
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
20  * USA. */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <pthread.h>
27 #include <assert.h>
28 #include <errno.h>
29 #include <time.h>
30 #include <unistd.h>
31 #ifndef HAVE_CLOCK_GETTIME
32 #include <sys/time.h>
33 #endif
34 #include "timed_thread.h"
35
36 /* Abstraction layer for timed threads */
37
38 static int now(struct timespec *);
39
40 /* private */
41 struct _timed_thread {
42         pthread_t thread;                               /* thread itself */
43         pthread_attr_t thread_attr;             /* thread attributes */
44         pthread_mutex_t cs_mutex;               /* critical section mutex */
45         pthread_mutex_t runnable_mutex; /* only for the runnable_cond */
46         pthread_cond_t runnable_cond;   /* signalled to stop the thread */
47         void *(*start_routine)(void *); /* thread function to run */
48         void *arg;                                              /* thread function argument */
49         struct timespec interval_time;  /* interval_usecs as a struct timespec */
50         struct timespec wait_time;              /* absolute future time next timed_thread_test will wait until */
51         int pipefd[2];
52 };
53
54 /* linked list of created threads */
55 typedef struct _timed_thread_list {
56         timed_thread *p_timed_thread;
57         timed_thread **addr_of_p_timed_thread;
58         struct _timed_thread_list *next;
59 } timed_thread_node, timed_thread_list;
60
61 static timed_thread_list *p_timed_thread_list_head = NULL;
62 static timed_thread_list *p_timed_thread_list_tail = NULL;
63
64 int timed_thread_readfd(timed_thread *p_timed_thread)
65 {
66         return p_timed_thread->pipefd[0];
67 }
68
69 static int now(struct timespec *abstime)
70 {
71 #ifndef HAVE_CLOCK_GETTIME
72         struct timeval tv;
73 #endif
74
75         if (!abstime) {
76                 return -1;
77         }
78
79 #ifdef HAVE_CLOCK_GETTIME
80         return clock_gettime(CLOCK_REALTIME, abstime);
81 #else
82         /* fallback to gettimeofday () */
83         if (gettimeofday(&tv, NULL) != 0) {
84                 return -1;
85         }
86
87         abstime->tv_sec = tv.tv_sec;
88         abstime->tv_nsec = tv.tv_usec * 1000;
89         return 0;
90 #endif
91 }
92
93 /* create a timed thread (object creation only) */
94 timed_thread *timed_thread_create(void *start_routine(void *), void *arg,
95                 unsigned int interval_usecs)
96 {
97         timed_thread *p_timed_thread;
98
99         assert(start_routine != NULL);
100         assert(interval_usecs >= MINIMUM_INTERVAL_USECS);
101
102         if ((p_timed_thread = calloc(sizeof(timed_thread), 1)) == 0) {
103                 return NULL;
104         }
105
106         /* create thread pipe (used to tell threads to die) */
107         if (pipe(p_timed_thread->pipefd)) {
108                 return NULL;
109         }
110
111         /* init attributes, e.g. joinable thread */
112         pthread_attr_init(&p_timed_thread->thread_attr);
113         pthread_attr_setdetachstate(&p_timed_thread->thread_attr,
114                         PTHREAD_CREATE_JOINABLE);
115         /* init mutexes */
116         pthread_mutex_init(&p_timed_thread->cs_mutex, NULL);
117         pthread_mutex_init(&p_timed_thread->runnable_mutex, NULL);
118         /* init cond */
119         pthread_cond_init(&p_timed_thread->runnable_cond, NULL);
120
121         p_timed_thread->start_routine = start_routine;
122         p_timed_thread->arg = arg;
123
124         /* set wait time to current time */
125         if (now(&p_timed_thread->wait_time)) {
126                 return NULL;
127         }
128
129         /* seconds portion of the microseconds interval */
130         p_timed_thread->interval_time.tv_sec = (time_t) (interval_usecs / 1000000);
131         /* remaining microseconds convert to nanoseconds */
132         p_timed_thread->interval_time.tv_nsec =
133                 (long) ((interval_usecs % 1000000) * 1000);
134
135         /* printf("interval_time.tv_sec = %li, .tv_nsec = %li\n",
136            p_timed_thread->interval_time.tv_sec,
137            p_timed_thread->interval_time.tv_nsec); */
138         return p_timed_thread;
139 }
140
141 /* run a timed thread (drop the thread and run it) */
142 int timed_thread_run(timed_thread *p_timed_thread)
143 {
144         return pthread_create(&p_timed_thread->thread, &p_timed_thread->thread_attr,
145                         p_timed_thread->start_routine, p_timed_thread->arg);
146 }
147
148 /* destroy a timed thread.
149  * optional addr_of_p_timed_thread to set callers pointer to NULL as a
150  * convenience. */
151 void timed_thread_destroy(timed_thread *p_timed_thread,
152                 timed_thread **addr_of_p_timed_thread)
153 {
154         assert(p_timed_thread != NULL);
155         assert((addr_of_p_timed_thread == NULL)
156                         || (*addr_of_p_timed_thread == p_timed_thread));
157
158         /* signal thread to stop */
159         pthread_mutex_lock(&p_timed_thread->runnable_mutex);
160         pthread_cond_signal(&p_timed_thread->runnable_cond);
161         pthread_mutex_unlock(&p_timed_thread->runnable_mutex);
162         write(p_timed_thread->pipefd[1], "die", 3);
163
164         /* join the terminating thread */
165         if (p_timed_thread->thread) {
166                 pthread_join(p_timed_thread->thread, NULL);
167         }
168
169         /* clean up */
170         pthread_attr_destroy(&p_timed_thread->thread_attr);
171         pthread_mutex_destroy(&p_timed_thread->cs_mutex);
172         pthread_mutex_destroy(&p_timed_thread->runnable_mutex);
173         pthread_cond_destroy(&p_timed_thread->runnable_cond);
174
175         free(p_timed_thread);
176         if (addr_of_p_timed_thread) {
177                 *addr_of_p_timed_thread = NULL;
178         }
179 }
180
181 /* lock a timed thread for critical section activity */
182 int timed_thread_lock(timed_thread *p_timed_thread)
183 {
184         assert(p_timed_thread != NULL);
185
186         return pthread_mutex_lock(&p_timed_thread->cs_mutex);
187 }
188
189 /* unlock a timed thread after critical section activity */
190 int timed_thread_unlock(timed_thread *p_timed_thread)
191 {
192         assert(p_timed_thread != NULL);
193
194         return pthread_mutex_unlock(&p_timed_thread->cs_mutex);
195 }
196
197 /* thread waits interval_usecs for runnable_cond to be signaled.
198  * returns 1 if signaled, -1 on error, and 0 otherwise.
199  * caller should call timed_thread_exit() on any non-zero return value. */
200 int timed_thread_test(timed_thread *p_timed_thread)
201 {
202         struct timespec now_time;
203         int rc;
204
205         assert(p_timed_thread != NULL);
206
207         /* acquire runnable_cond mutex */
208         if (pthread_mutex_lock(&p_timed_thread->runnable_mutex)) {
209                 /* could not acquire runnable_cond mutex,
210                  * so tell caller to exit thread */
211                 return -1;
212         }
213
214         /* release mutex and wait until future time for runnable_cond to signal */
215         rc = pthread_cond_timedwait(&p_timed_thread->runnable_cond,
216                         &p_timed_thread->runnable_mutex, &p_timed_thread->wait_time);
217         /* mutex re-acquired, so release it */
218         pthread_mutex_unlock(&p_timed_thread->runnable_mutex);
219         
220         if (now(&now_time)) {
221                 return -1;
222         }
223
224         if (rc == 0) {
225                 /* runnable_cond was signaled, so tell caller to exit thread */
226                 return 1;
227         }
228
229         /* absolute future time for next pass */
230         p_timed_thread->wait_time.tv_sec += p_timed_thread->interval_time.tv_sec;
231         p_timed_thread->wait_time.tv_nsec += p_timed_thread->interval_time.tv_nsec;
232         p_timed_thread->wait_time.tv_sec += p_timed_thread->wait_time.tv_nsec / 1000000000;
233         p_timed_thread->wait_time.tv_nsec = p_timed_thread->wait_time.tv_nsec % 1000000000;
234
235         /* ensure our future wait time is sane */
236         if (p_timed_thread->wait_time.tv_sec > (now_time.tv_sec + p_timed_thread->interval_time.tv_sec) || p_timed_thread->wait_time.tv_sec < now_time.tv_sec) {
237                 p_timed_thread->wait_time.tv_sec = now_time.tv_sec + p_timed_thread->interval_time.tv_sec;
238                 p_timed_thread->wait_time.tv_nsec = now_time.tv_nsec + p_timed_thread->interval_time.tv_nsec;
239                 p_timed_thread->wait_time.tv_sec += p_timed_thread->wait_time.tv_nsec / 1000000000;
240                 p_timed_thread->wait_time.tv_nsec = p_timed_thread->wait_time.tv_nsec % 1000000000;
241         }
242
243         /* tell caller not to exit yet */
244         return 0;
245 }
246
247 /* exit a timed thread */
248 void timed_thread_exit(timed_thread *p_timed_thread)
249 {
250         assert(p_timed_thread != NULL);
251
252         close(p_timed_thread->pipefd[0]);
253         close(p_timed_thread->pipefd[1]);
254
255         pthread_exit(NULL);
256 }
257
258 /* register a timed thread for future destruction via
259  * timed_thread_destroy_registered_threads() */
260 int timed_thread_register(timed_thread *p_timed_thread,
261                 timed_thread **addr_of_p_timed_thread)
262 {
263         timed_thread_node *p_node;
264
265         assert((addr_of_p_timed_thread == NULL)
266                         || (*addr_of_p_timed_thread == p_timed_thread));
267
268         if ((p_node = calloc(sizeof(timed_thread_node), 1)) == 0) {
269                 return 0;
270         }
271
272         p_node->p_timed_thread = p_timed_thread;
273         p_node->addr_of_p_timed_thread = addr_of_p_timed_thread;
274         p_node->next = NULL;
275
276         if (!p_timed_thread_list_tail) {
277                 /* first node of empty list */
278                 p_timed_thread_list_tail = p_node;
279                 p_timed_thread_list_head = p_node;
280         } else {
281                 /* add node to tail of non-empty list */
282                 p_timed_thread_list_tail->next = p_node;
283                 p_timed_thread_list_tail = p_node;
284         }
285
286         return 0;
287 }
288
289 /* destroy all registered timed threads */
290 void timed_thread_destroy_registered_threads(void)
291 {
292         timed_thread_node *p_node, *p_next;
293
294         for (p_node = p_timed_thread_list_head; p_node; p_node = p_next) {
295                 p_next = p_node->next;
296                 timed_thread_destroy(p_node->p_timed_thread,
297                                 p_node->addr_of_p_timed_thread);
298                 free(p_node);
299                 p_node = NULL;
300         }
301
302         p_timed_thread_list_head = NULL;
303         p_timed_thread_list_tail = NULL;
304 }