]>
git.saurik.com Git - redis.git/blob - ae.c
d5eff76c85b077b637b0d508678841a7c4d30c79
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.
5 * Copyright (c) 2006-2009, Salvatore Sanfilippo <antirez at gmail dot com>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
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.
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.
35 #include <sys/types.h>
42 aeEventLoop
*aeCreateEventLoop(void) {
43 aeEventLoop
*eventLoop
;
45 eventLoop
= zmalloc(sizeof(*eventLoop
));
46 if (!eventLoop
) return NULL
;
47 eventLoop
->fileEventHead
= NULL
;
48 eventLoop
->timeEventHead
= NULL
;
49 eventLoop
->timeEventNextId
= 0;
54 void aeDeleteEventLoop(aeEventLoop
*eventLoop
) {
58 void aeStop(aeEventLoop
*eventLoop
) {
62 int aeCreateFileEvent(aeEventLoop
*eventLoop
, int fd
, int mask
,
63 aeFileProc
*proc
, void *clientData
,
64 aeEventFinalizerProc
*finalizerProc
)
68 fe
= zmalloc(sizeof(*fe
));
69 if (fe
== NULL
) return AE_ERR
;
73 fe
->finalizerProc
= finalizerProc
;
74 fe
->clientData
= clientData
;
75 fe
->next
= eventLoop
->fileEventHead
;
76 eventLoop
->fileEventHead
= fe
;
80 void aeDeleteFileEvent(aeEventLoop
*eventLoop
, int fd
, int mask
)
82 aeFileEvent
*fe
, *prev
= NULL
;
84 fe
= eventLoop
->fileEventHead
;
86 if (fe
->fd
== fd
&& fe
->mask
== mask
) {
88 eventLoop
->fileEventHead
= fe
->next
;
90 prev
->next
= fe
->next
;
91 if (fe
->finalizerProc
)
92 fe
->finalizerProc(eventLoop
, fe
->clientData
);
101 static void aeGetTime(long *seconds
, long *milliseconds
)
105 gettimeofday(&tv
, NULL
);
106 *seconds
= tv
.tv_sec
;
107 *milliseconds
= tv
.tv_usec
/1000;
110 static void aeAddMillisecondsToNow(long long milliseconds
, long *sec
, long *ms
) {
111 long cur_sec
, cur_ms
, when_sec
, when_ms
;
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) {
124 long long aeCreateTimeEvent(aeEventLoop
*eventLoop
, long long milliseconds
,
125 aeTimeProc
*proc
, void *clientData
,
126 aeEventFinalizerProc
*finalizerProc
)
128 long long id
= eventLoop
->timeEventNextId
++;
131 te
= zmalloc(sizeof(*te
));
132 if (te
== NULL
) return AE_ERR
;
134 aeAddMillisecondsToNow(milliseconds
,&te
->when_sec
,&te
->when_ms
);
136 te
->finalizerProc
= finalizerProc
;
137 te
->clientData
= clientData
;
138 te
->next
= eventLoop
->timeEventHead
;
139 eventLoop
->timeEventHead
= te
;
143 int aeDeleteTimeEvent(aeEventLoop
*eventLoop
, long long id
)
145 aeTimeEvent
*te
, *prev
= NULL
;
147 te
= eventLoop
->timeEventHead
;
151 eventLoop
->timeEventHead
= te
->next
;
153 prev
->next
= te
->next
;
154 if (te
->finalizerProc
)
155 te
->finalizerProc(eventLoop
, te
->clientData
);
162 return AE_ERR
; /* NO event with the specified ID found */
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.
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)).
176 static aeTimeEvent
*aeSearchNearestTimer(aeEventLoop
*eventLoop
)
178 aeTimeEvent
*te
= eventLoop
->timeEventHead
;
179 aeTimeEvent
*nearest
= NULL
;
182 if (!nearest
|| te
->when_sec
< nearest
->when_sec
||
183 (te
->when_sec
== nearest
->when_sec
&&
184 te
->when_ms
< nearest
->when_ms
))
191 /* Process time events */
192 static int processTimeEvents(aeEventLoop
*eventLoop
) {
197 te
= eventLoop
->timeEventHead
;
198 maxId
= eventLoop
->timeEventNextId
-1;
200 long now_sec
, now_ms
;
203 if (te
->id
> maxId
) {
207 aeGetTime(&now_sec
, &now_ms
);
208 if (now_sec
> te
->when_sec
||
209 (now_sec
== te
->when_sec
&& now_ms
>= te
->when_ms
))
214 retval
= te
->timeProc(eventLoop
, id
, te
->clientData
);
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.
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
);
232 aeDeleteTimeEvent(eventLoop
, id
);
234 te
= eventLoop
->timeEventHead
;
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).
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.
254 * The function returns the number of events processed. */
255 int aeProcessEvents(aeEventLoop
*eventLoop
, int flags
)
257 int maxfd
= 0, numfd
= 0, processed
= 0;
258 fd_set rfds
, wfds
, efds
;
259 aeFileEvent
*fe
= eventLoop
->fileEventHead
;
261 /* Nothing to do? return ASAP */
262 if (!(flags
& AE_TIME_EVENTS
) && !(flags
& AE_FILE_EVENTS
)) return 0;
268 /* Check file events */
269 if (flags
& AE_FILE_EVENTS
) {
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
;
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
283 if (numfd
|| ((flags
& AE_TIME_EVENTS
) && !(flags
& AE_DONT_WAIT
))) {
285 aeTimeEvent
*shortest
= NULL
;
286 struct timeval tv
, *tvp
;
288 if (flags
& AE_TIME_EVENTS
&& !(flags
& AE_DONT_WAIT
))
289 shortest
= aeSearchNearestTimer(eventLoop
);
291 long now_sec
, now_ms
;
293 /* Calculate the time missing for the nearest
295 aeGetTime(&now_sec
, &now_ms
);
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;
302 tvp
->tv_usec
= (shortest
->when_ms
- now_ms
)*1000;
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
308 if (flags
& AE_DONT_WAIT
) {
309 tv
.tv_sec
= tv
.tv_usec
= 0;
312 /* Otherwise we can block */
313 tvp
= NULL
; /* wait forever */
317 retval
= select(maxfd
+1, &rfds
, &wfds
, &efds
, tvp
);
319 fe
= eventLoop
->fileEventHead
;
321 int fd
= (int) fe
->fd
;
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
)))
329 if (fe
->mask
& AE_READABLE
&& FD_ISSET(fd
, &rfds
))
331 if (fe
->mask
& AE_WRITABLE
&& FD_ISSET(fd
, &wfds
))
333 if (fe
->mask
& AE_EXCEPTION
&& FD_ISSET(fd
, &efds
))
334 mask
|= AE_EXCEPTION
;
335 fe
->fileProc(eventLoop
, fe
->fd
, fe
->clientData
, mask
);
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
;
351 /* Check time events */
352 if (flags
& AE_TIME_EVENTS
)
353 processed
+= processTimeEvents(eventLoop
);
355 return processed
; /* return the number of processed file/time events */
358 /* Wait for millseconds until the given file descriptor becomes
359 * writable/readable/exception */
360 int aeWait(int fd
, int mask
, long long milliseconds
) {
362 fd_set rfds
, wfds
, efds
;
363 int retmask
= 0, retval
;
365 tv
.tv_sec
= milliseconds
/1000;
366 tv
.tv_usec
= (milliseconds%1000
)*1000;
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
;
384 void aeMain(aeEventLoop
*eventLoop
)
387 while (!eventLoop
->stop
)
388 aeProcessEvents(eventLoop
, AE_ALL_EVENTS
);