]> git.saurik.com Git - redis.git/blob - ae.c
d5eff76c85b077b637b0d508678841a7c4d30c79
[redis.git] / ae.c
1 /* A simple event-driven programming library. Originally I wrote this code
2 * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated
3 * it in form of a library for easy reuse.
4 *
5 * Copyright (c) 2006-2009, Salvatore Sanfilippo <antirez at gmail dot com>
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
10 *
11 * * Redistributions of source code must retain the above copyright notice,
12 * this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * * Neither the name of Redis nor the names of its contributors may be used
17 * to endorse or promote products derived from this software without
18 * specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 #include <stdio.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <unistd.h>
37 #include <stdlib.h>
38
39 #include "ae.h"
40 #include "zmalloc.h"
41
42 aeEventLoop *aeCreateEventLoop(void) {
43 aeEventLoop *eventLoop;
44
45 eventLoop = zmalloc(sizeof(*eventLoop));
46 if (!eventLoop) return NULL;
47 eventLoop->fileEventHead = NULL;
48 eventLoop->timeEventHead = NULL;
49 eventLoop->timeEventNextId = 0;
50 eventLoop->stop = 0;
51 return eventLoop;
52 }
53
54 void aeDeleteEventLoop(aeEventLoop *eventLoop) {
55 zfree(eventLoop);
56 }
57
58 void aeStop(aeEventLoop *eventLoop) {
59 eventLoop->stop = 1;
60 }
61
62 int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask,
63 aeFileProc *proc, void *clientData,
64 aeEventFinalizerProc *finalizerProc)
65 {
66 aeFileEvent *fe;
67
68 fe = zmalloc(sizeof(*fe));
69 if (fe == NULL) return AE_ERR;
70 fe->fd = fd;
71 fe->mask = mask;
72 fe->fileProc = proc;
73 fe->finalizerProc = finalizerProc;
74 fe->clientData = clientData;
75 fe->next = eventLoop->fileEventHead;
76 eventLoop->fileEventHead = fe;
77 return AE_OK;
78 }
79
80 void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask)
81 {
82 aeFileEvent *fe, *prev = NULL;
83
84 fe = eventLoop->fileEventHead;
85 while(fe) {
86 if (fe->fd == fd && fe->mask == mask) {
87 if (prev == NULL)
88 eventLoop->fileEventHead = fe->next;
89 else
90 prev->next = fe->next;
91 if (fe->finalizerProc)
92 fe->finalizerProc(eventLoop, fe->clientData);
93 zfree(fe);
94 return;
95 }
96 prev = fe;
97 fe = fe->next;
98 }
99 }
100
101 static void aeGetTime(long *seconds, long *milliseconds)
102 {
103 struct timeval tv;
104
105 gettimeofday(&tv, NULL);
106 *seconds = tv.tv_sec;
107 *milliseconds = tv.tv_usec/1000;
108 }
109
110 static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) {
111 long cur_sec, cur_ms, when_sec, when_ms;
112
113 aeGetTime(&cur_sec, &cur_ms);
114 when_sec = cur_sec + milliseconds/1000;
115 when_ms = cur_ms + milliseconds%1000;
116 if (when_ms >= 1000) {
117 when_sec ++;
118 when_ms -= 1000;
119 }
120 *sec = when_sec;
121 *ms = when_ms;
122 }
123
124 long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds,
125 aeTimeProc *proc, void *clientData,
126 aeEventFinalizerProc *finalizerProc)
127 {
128 long long id = eventLoop->timeEventNextId++;
129 aeTimeEvent *te;
130
131 te = zmalloc(sizeof(*te));
132 if (te == NULL) return AE_ERR;
133 te->id = id;
134 aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms);
135 te->timeProc = proc;
136 te->finalizerProc = finalizerProc;
137 te->clientData = clientData;
138 te->next = eventLoop->timeEventHead;
139 eventLoop->timeEventHead = te;
140 return id;
141 }
142
143 int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id)
144 {
145 aeTimeEvent *te, *prev = NULL;
146
147 te = eventLoop->timeEventHead;
148 while(te) {
149 if (te->id == id) {
150 if (prev == NULL)
151 eventLoop->timeEventHead = te->next;
152 else
153 prev->next = te->next;
154 if (te->finalizerProc)
155 te->finalizerProc(eventLoop, te->clientData);
156 zfree(te);
157 return AE_OK;
158 }
159 prev = te;
160 te = te->next;
161 }
162 return AE_ERR; /* NO event with the specified ID found */
163 }
164
165 /* Search the first timer to fire.
166 * This operation is useful to know how many time the select can be
167 * put in sleep without to delay any event.
168 * If there are no timers NULL is returned.
169 *
170 * Note that's O(N) since time events are unsorted.
171 * Possible optimizations (not needed by Redis so far, but...):
172 * 1) Insert the event in order, so that the nearest is just the head.
173 * Much better but still insertion or deletion of timers is O(N).
174 * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)).
175 */
176 static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop)
177 {
178 aeTimeEvent *te = eventLoop->timeEventHead;
179 aeTimeEvent *nearest = NULL;
180
181 while(te) {
182 if (!nearest || te->when_sec < nearest->when_sec ||
183 (te->when_sec == nearest->when_sec &&
184 te->when_ms < nearest->when_ms))
185 nearest = te;
186 te = te->next;
187 }
188 return nearest;
189 }
190
191 /* Process time events */
192 static int processTimeEvents(aeEventLoop *eventLoop) {
193 int processed = 0;
194 aeTimeEvent *te;
195 long long maxId;
196
197 te = eventLoop->timeEventHead;
198 maxId = eventLoop->timeEventNextId-1;
199 while(te) {
200 long now_sec, now_ms;
201 long long id;
202
203 if (te->id > maxId) {
204 te = te->next;
205 continue;
206 }
207 aeGetTime(&now_sec, &now_ms);
208 if (now_sec > te->when_sec ||
209 (now_sec == te->when_sec && now_ms >= te->when_ms))
210 {
211 int retval;
212
213 id = te->id;
214 retval = te->timeProc(eventLoop, id, te->clientData);
215 processed++;
216 /* After an event is processed our time event list may
217 * no longer be the same, so we restart from head.
218 * Still we make sure to don't process events registered
219 * by event handlers itself in order to don't loop forever.
220 * To do so we saved the max ID we want to handle.
221 *
222 * FUTURE OPTIMIZATIONS:
223 * Note that this is NOT great algorithmically. Redis uses
224 * a single time event so it's not a problem but the right
225 * way to do this is to add the new elements on head, and
226 * to flag deleted elements in a special way for later
227 * deletion (putting references to the nodes to delete into
228 * another linked list). */
229 if (retval != AE_NOMORE) {
230 aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms);
231 } else {
232 aeDeleteTimeEvent(eventLoop, id);
233 }
234 te = eventLoop->timeEventHead;
235 } else {
236 te = te->next;
237 }
238 }
239 return processed;
240 }
241
242 /* Process every pending time event, then every pending file event
243 * (that may be registered by time event callbacks just processed).
244 * Without special flags the function sleeps until some file event
245 * fires, or when the next time event occurrs (if any).
246 *
247 * If flags is 0, the function does nothing and returns.
248 * if flags has AE_ALL_EVENTS set, all the kind of events are processed.
249 * if flags has AE_FILE_EVENTS set, file events are processed.
250 * if flags has AE_TIME_EVENTS set, time events are processed.
251 * if flags has AE_DONT_WAIT set the function returns ASAP until all
252 * the events that's possible to process without to wait are processed.
253 *
254 * The function returns the number of events processed. */
255 int aeProcessEvents(aeEventLoop *eventLoop, int flags)
256 {
257 int maxfd = 0, numfd = 0, processed = 0;
258 fd_set rfds, wfds, efds;
259 aeFileEvent *fe = eventLoop->fileEventHead;
260
261 /* Nothing to do? return ASAP */
262 if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0;
263
264 FD_ZERO(&rfds);
265 FD_ZERO(&wfds);
266 FD_ZERO(&efds);
267
268 /* Check file events */
269 if (flags & AE_FILE_EVENTS) {
270 while (fe != NULL) {
271 if (fe->mask & AE_READABLE) FD_SET(fe->fd, &rfds);
272 if (fe->mask & AE_WRITABLE) FD_SET(fe->fd, &wfds);
273 if (fe->mask & AE_EXCEPTION) FD_SET(fe->fd, &efds);
274 if (maxfd < fe->fd) maxfd = fe->fd;
275 numfd++;
276 fe = fe->next;
277 }
278 }
279 /* Note that we want call select() even if there are no
280 * file events to process as long as we want to process time
281 * events, in order to sleep until the next time event is ready
282 * to fire. */
283 if (numfd || ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) {
284 int retval;
285 aeTimeEvent *shortest = NULL;
286 struct timeval tv, *tvp;
287
288 if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT))
289 shortest = aeSearchNearestTimer(eventLoop);
290 if (shortest) {
291 long now_sec, now_ms;
292
293 /* Calculate the time missing for the nearest
294 * timer to fire. */
295 aeGetTime(&now_sec, &now_ms);
296 tvp = &tv;
297 tvp->tv_sec = shortest->when_sec - now_sec;
298 if (shortest->when_ms < now_ms) {
299 tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000;
300 tvp->tv_sec --;
301 } else {
302 tvp->tv_usec = (shortest->when_ms - now_ms)*1000;
303 }
304 } else {
305 /* If we have to check for events but need to return
306 * ASAP because of AE_DONT_WAIT we need to se the timeout
307 * to zero */
308 if (flags & AE_DONT_WAIT) {
309 tv.tv_sec = tv.tv_usec = 0;
310 tvp = &tv;
311 } else {
312 /* Otherwise we can block */
313 tvp = NULL; /* wait forever */
314 }
315 }
316
317 retval = select(maxfd+1, &rfds, &wfds, &efds, tvp);
318 if (retval > 0) {
319 fe = eventLoop->fileEventHead;
320 while(fe != NULL) {
321 int fd = (int) fe->fd;
322
323 if ((fe->mask & AE_READABLE && FD_ISSET(fd, &rfds)) ||
324 (fe->mask & AE_WRITABLE && FD_ISSET(fd, &wfds)) ||
325 (fe->mask & AE_EXCEPTION && FD_ISSET(fd, &efds)))
326 {
327 int mask = 0;
328
329 if (fe->mask & AE_READABLE && FD_ISSET(fd, &rfds))
330 mask |= AE_READABLE;
331 if (fe->mask & AE_WRITABLE && FD_ISSET(fd, &wfds))
332 mask |= AE_WRITABLE;
333 if (fe->mask & AE_EXCEPTION && FD_ISSET(fd, &efds))
334 mask |= AE_EXCEPTION;
335 fe->fileProc(eventLoop, fe->fd, fe->clientData, mask);
336 processed++;
337 /* After an event is processed our file event list
338 * may no longer be the same, so what we do
339 * is to clear the bit for this file descriptor and
340 * restart again from the head. */
341 fe = eventLoop->fileEventHead;
342 FD_CLR(fd, &rfds);
343 FD_CLR(fd, &wfds);
344 FD_CLR(fd, &efds);
345 } else {
346 fe = fe->next;
347 }
348 }
349 }
350 }
351 /* Check time events */
352 if (flags & AE_TIME_EVENTS)
353 processed += processTimeEvents(eventLoop);
354
355 return processed; /* return the number of processed file/time events */
356 }
357
358 /* Wait for millseconds until the given file descriptor becomes
359 * writable/readable/exception */
360 int aeWait(int fd, int mask, long long milliseconds) {
361 struct timeval tv;
362 fd_set rfds, wfds, efds;
363 int retmask = 0, retval;
364
365 tv.tv_sec = milliseconds/1000;
366 tv.tv_usec = (milliseconds%1000)*1000;
367 FD_ZERO(&rfds);
368 FD_ZERO(&wfds);
369 FD_ZERO(&efds);
370
371 if (mask & AE_READABLE) FD_SET(fd,&rfds);
372 if (mask & AE_WRITABLE) FD_SET(fd,&wfds);
373 if (mask & AE_EXCEPTION) FD_SET(fd,&efds);
374 if ((retval = select(fd+1, &rfds, &wfds, &efds, &tv)) > 0) {
375 if (FD_ISSET(fd,&rfds)) retmask |= AE_READABLE;
376 if (FD_ISSET(fd,&wfds)) retmask |= AE_WRITABLE;
377 if (FD_ISSET(fd,&efds)) retmask |= AE_EXCEPTION;
378 return retmask;
379 } else {
380 return retval;
381 }
382 }
383
384 void aeMain(aeEventLoop *eventLoop)
385 {
386 eventLoop->stop = 0;
387 while (!eventLoop->stop)
388 aeProcessEvents(eventLoop, AE_ALL_EVENTS);
389 }