Fix timed thread race condition, seen esp. on new kernel scheduler (cfs).
[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 /* private */
39 struct _timed_thread 
40 {
41   pthread_t thread;               /* thread itself */
42   pthread_attr_t thread_attr;     /* thread attributes */
43   pthread_mutex_t cs_mutex;       /* critical section mutex */
44   pthread_mutex_t runnable_mutex; /* only for the runnable_cond */
45   pthread_cond_t runnable_cond;   /* signalled to stop the thread */
46   unsigned int interval_usecs;    /* timed_thread_test() wait interval in microseconds */
47   void *(*start_routine)(void*);  /* thread function to run */
48   void *arg;                      /* thread function argument */
49 };
50
51 /* linked list of created threads */
52 typedef struct _timed_thread_list
53 {
54   timed_thread *p_timed_thread;
55   timed_thread **addr_of_p_timed_thread;
56   struct _timed_thread_list *next;
57 } timed_thread_node, timed_thread_list;
58
59 static timed_thread_list *p_timed_thread_list_head = NULL;
60 static timed_thread_list *p_timed_thread_list_tail = NULL;
61
62
63 /* create a timed thread (object creation only) */
64 timed_thread* 
65 timed_thread_create (void *(*start_routine)(void*), void *arg, unsigned int interval_usecs)
66 {
67   timed_thread *p_timed_thread;
68
69   assert ((start_routine != NULL) && (interval_usecs >= MINIMUM_INTERVAL_USECS));
70
71   if ((p_timed_thread = calloc (sizeof(timed_thread), 1)) == 0)
72     return NULL;
73
74   /* init attributes, e.g. joinable thread */
75   pthread_attr_init (&p_timed_thread->thread_attr);
76   pthread_attr_setdetachstate (&p_timed_thread->thread_attr, PTHREAD_CREATE_JOINABLE);
77   /* init mutexes */
78   pthread_mutex_init (&p_timed_thread->cs_mutex, NULL);
79   pthread_mutex_init (&p_timed_thread->runnable_mutex, NULL);
80   /* init cond */
81   pthread_cond_init (&p_timed_thread->runnable_cond, NULL);
82
83   p_timed_thread->interval_usecs = interval_usecs;
84   p_timed_thread->start_routine = start_routine;
85   p_timed_thread->arg = arg;
86
87   return p_timed_thread;
88 }
89
90 /* run a timed thread (drop the thread and run it) */
91 int 
92 timed_thread_run (timed_thread* p_timed_thread)
93 {
94   return pthread_create (&p_timed_thread->thread, &p_timed_thread->thread_attr,
95                          p_timed_thread->start_routine, p_timed_thread->arg);
96 }
97
98 /* destroy a timed thread.
99  * optional addr_of_p_timed_thread to set callers pointer to NULL as a convenience. */
100 void 
101 timed_thread_destroy (timed_thread* p_timed_thread, timed_thread** addr_of_p_timed_thread)
102 {
103   assert (p_timed_thread != NULL);
104   assert ((addr_of_p_timed_thread == NULL) || (*addr_of_p_timed_thread == p_timed_thread));
105
106   /* signal thread to stop */
107   pthread_mutex_lock (&p_timed_thread->runnable_mutex);
108   pthread_cond_signal (&p_timed_thread->runnable_cond);
109   pthread_mutex_unlock (&p_timed_thread->runnable_mutex);
110
111   /* join the terminating thread */
112   pthread_join (p_timed_thread->thread, NULL);
113
114   /* clean up */
115   pthread_attr_destroy (&p_timed_thread->thread_attr);
116   pthread_mutex_destroy (&p_timed_thread->cs_mutex);
117   pthread_mutex_destroy (&p_timed_thread->runnable_mutex);
118   pthread_cond_destroy (&p_timed_thread->runnable_cond);
119
120   free (p_timed_thread);
121   if (addr_of_p_timed_thread)
122     *addr_of_p_timed_thread = NULL;
123 }
124
125
126 /* lock a timed thread for critical section activity */
127 int
128 timed_thread_lock (timed_thread* p_timed_thread)
129 {
130   assert (p_timed_thread != NULL);
131
132   return pthread_mutex_lock (&p_timed_thread->cs_mutex);
133 }
134
135
136 /* unlock a timed thread after critical section activity */
137 int
138 timed_thread_unlock (timed_thread* p_timed_thread)
139 {
140   assert (p_timed_thread != NULL);
141
142   return pthread_mutex_unlock (&p_timed_thread->cs_mutex);
143 }
144
145
146 /* thread waits interval_usecs for runnable_cond to be signaled.  returns 1 if signaled, 
147  * -1 on error, and 0 otherwise.  caller should call timed_thread_exit() on any non-zero 
148  * return value. */
149 int 
150 timed_thread_test (timed_thread* p_timed_thread)
151 {
152   struct timespec abstime, reltime;
153   int rc;
154
155   assert (p_timed_thread != NULL);
156
157   /* acquire runnable_cond mutex */
158   if (pthread_mutex_lock (&p_timed_thread->runnable_mutex))
159     return (-1);  /* could not acquire runnable_cond mutex, so tell caller to exit thread */
160
161   /* get the absolute time in the future we stop waiting for condition to signal */
162 #ifdef HAVE_CLOCK_GETTIME
163   clock_gettime (CLOCK_REALTIME, &abstime);
164 #else
165   {
166     /* fallback to gettimeofday () */
167     struct timeval tv;
168     if (gettimeofday (&tv, NULL) != 0)
169     {
170       pthread_mutex_unlock (&p_timed_thread->runnable_mutex);
171       return (-1);
172     }
173
174     abstime.tv_sec = tv.tv_sec;
175     abstime.tv_nsec = tv.tv_usec * 1000;
176   }
177 #endif
178   /* seconds portion of the microseconds interval */
179   reltime.tv_sec = (time_t)(p_timed_thread->interval_usecs / 1000000);
180   /* remaining microseconds convert to nanoseconds */
181   reltime.tv_nsec = (long)((p_timed_thread->interval_usecs % 1000000) * 1000);
182   /* absolute future time */
183   abstime.tv_sec += reltime.tv_sec;
184   abstime.tv_nsec += reltime.tv_nsec;
185
186   /* release mutex and wait until future time for runnable_cond to signal */
187   rc = pthread_cond_timedwait (&p_timed_thread->runnable_cond,
188                                &p_timed_thread->runnable_mutex,
189                                &abstime);
190   /* mutex re-acquired, so release it */
191   pthread_mutex_unlock (&p_timed_thread->runnable_mutex);
192
193   if (rc==0)
194     return 1; /* runnable_cond was signaled, so tell caller to exit thread */
195
196   /* tell caller not to exit yet */
197   return 0;
198 }
199
200
201 /* exit a timed thread */
202 void 
203 timed_thread_exit (timed_thread* p_timed_thread)
204 {
205   assert (p_timed_thread != NULL);
206
207   pthread_exit (NULL);
208 }
209
210
211 /* register a timed thread for future destruction via timed_thread_destroy_registered_threads() */
212 int 
213 timed_thread_register (timed_thread* p_timed_thread, timed_thread** addr_of_p_timed_thread)
214 {
215   timed_thread_node *p_node;
216
217   assert (p_timed_thread != NULL);
218   assert ((addr_of_p_timed_thread == NULL) || (*addr_of_p_timed_thread == p_timed_thread));
219
220   if ((p_node = calloc (sizeof (timed_thread_node), 1)) == 0)
221     return 0;
222     
223   p_node->p_timed_thread = p_timed_thread;
224   p_node->addr_of_p_timed_thread = addr_of_p_timed_thread;
225   p_node->next = NULL;
226
227   if (!p_timed_thread_list_tail)
228   {
229     /* first node of empty list */
230     p_timed_thread_list_tail = p_node;
231     p_timed_thread_list_head = p_node;
232   }
233   else
234   {
235     /* add node to tail of non-empty list */
236     p_timed_thread_list_tail->next = p_node;
237     p_timed_thread_list_tail = p_node;
238   }
239
240   return 0;
241 }
242
243
244 /* destroy all registered timed threads */
245 void 
246 timed_thread_destroy_registered_threads (void)
247 {
248   timed_thread_node *p_node, *p_next;
249
250   for (p_node=p_timed_thread_list_head;
251        p_node;
252        p_node=p_next)
253   {
254     p_next = p_node->next;
255     timed_thread_destroy (p_node->p_timed_thread, p_node->addr_of_p_timed_thread);
256     free (p_node);
257     p_node = NULL;
258   }
259
260   p_timed_thread_list_head = NULL;
261   p_timed_thread_list_tail = NULL;
262 }
263