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