]>
git.saurik.com Git - redis.git/blob - 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.
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>
43 /* Include the best multiplexing layer supported by this system.
44 * The following should be ordered by performances, descending. */
48 #include "ae_select.c"
51 aeEventLoop
*aeCreateEventLoop(void) {
52 aeEventLoop
*eventLoop
;
55 eventLoop
= zmalloc(sizeof(*eventLoop
));
56 if (!eventLoop
) return NULL
;
57 eventLoop
->timeEventHead
= NULL
;
58 eventLoop
->timeEventNextId
= 0;
60 eventLoop
->maxfd
= -1;
61 if (aeApiCreate(eventLoop
) == -1) {
65 /* Events with mask == AE_NONE are not set. So let's initialize the
67 for (i
= 0; i
< AE_SETSIZE
; i
++)
68 eventLoop
->events
[i
].mask
= AE_NONE
;
72 void aeDeleteEventLoop(aeEventLoop
*eventLoop
) {
77 void aeStop(aeEventLoop
*eventLoop
) {
81 int aeCreateFileEvent(aeEventLoop
*eventLoop
, int fd
, int mask
,
82 aeFileProc
*proc
, void *clientData
)
84 if (fd
>= AE_SETSIZE
) return AE_ERR
;
85 aeFileEvent
*fe
= &eventLoop
->events
[fd
];
87 if (aeApiAddEvent(eventLoop
, fd
, mask
) == -1)
90 if (mask
& AE_READABLE
) fe
->rfileProc
= proc
;
91 if (mask
& AE_WRITABLE
) fe
->wfileProc
= proc
;
92 if (mask
& AE_EXCEPTION
) fe
->efileProc
= proc
;
93 fe
->clientData
= clientData
;
94 if (fd
> eventLoop
->maxfd
)
95 eventLoop
->maxfd
= fd
;
99 void aeDeleteFileEvent(aeEventLoop
*eventLoop
, int fd
, int mask
)
101 if (fd
>= AE_SETSIZE
) return;
102 aeFileEvent
*fe
= &eventLoop
->events
[fd
];
104 if (fe
->mask
== AE_NONE
) return;
105 fe
->mask
= fe
->mask
& (~mask
);
106 if (fd
== eventLoop
->maxfd
&& fe
->mask
== AE_NONE
) {
107 /* Update the max fd */
110 for (j
= eventLoop
->maxfd
-1; j
>= 0; j
--)
111 if (eventLoop
->events
[j
].mask
!= AE_NONE
) break;
112 eventLoop
->maxfd
= j
;
114 aeApiDelEvent(eventLoop
, fd
, mask
);
117 static void aeGetTime(long *seconds
, long *milliseconds
)
121 gettimeofday(&tv
, NULL
);
122 *seconds
= tv
.tv_sec
;
123 *milliseconds
= tv
.tv_usec
/1000;
126 static void aeAddMillisecondsToNow(long long milliseconds
, long *sec
, long *ms
) {
127 long cur_sec
, cur_ms
, when_sec
, when_ms
;
129 aeGetTime(&cur_sec
, &cur_ms
);
130 when_sec
= cur_sec
+ milliseconds
/1000;
131 when_ms
= cur_ms
+ milliseconds%1000
;
132 if (when_ms
>= 1000) {
140 long long aeCreateTimeEvent(aeEventLoop
*eventLoop
, long long milliseconds
,
141 aeTimeProc
*proc
, void *clientData
,
142 aeEventFinalizerProc
*finalizerProc
)
144 long long id
= eventLoop
->timeEventNextId
++;
147 te
= zmalloc(sizeof(*te
));
148 if (te
== NULL
) return AE_ERR
;
150 aeAddMillisecondsToNow(milliseconds
,&te
->when_sec
,&te
->when_ms
);
152 te
->finalizerProc
= finalizerProc
;
153 te
->clientData
= clientData
;
154 te
->next
= eventLoop
->timeEventHead
;
155 eventLoop
->timeEventHead
= te
;
159 int aeDeleteTimeEvent(aeEventLoop
*eventLoop
, long long id
)
161 aeTimeEvent
*te
, *prev
= NULL
;
163 te
= eventLoop
->timeEventHead
;
167 eventLoop
->timeEventHead
= te
->next
;
169 prev
->next
= te
->next
;
170 if (te
->finalizerProc
)
171 te
->finalizerProc(eventLoop
, te
->clientData
);
178 return AE_ERR
; /* NO event with the specified ID found */
181 /* Search the first timer to fire.
182 * This operation is useful to know how many time the select can be
183 * put in sleep without to delay any event.
184 * If there are no timers NULL is returned.
186 * Note that's O(N) since time events are unsorted.
187 * Possible optimizations (not needed by Redis so far, but...):
188 * 1) Insert the event in order, so that the nearest is just the head.
189 * Much better but still insertion or deletion of timers is O(N).
190 * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)).
192 static aeTimeEvent
*aeSearchNearestTimer(aeEventLoop
*eventLoop
)
194 aeTimeEvent
*te
= eventLoop
->timeEventHead
;
195 aeTimeEvent
*nearest
= NULL
;
198 if (!nearest
|| te
->when_sec
< nearest
->when_sec
||
199 (te
->when_sec
== nearest
->when_sec
&&
200 te
->when_ms
< nearest
->when_ms
))
207 /* Process time events */
208 static int processTimeEvents(aeEventLoop
*eventLoop
) {
213 te
= eventLoop
->timeEventHead
;
214 maxId
= eventLoop
->timeEventNextId
-1;
216 long now_sec
, now_ms
;
219 if (te
->id
> maxId
) {
223 aeGetTime(&now_sec
, &now_ms
);
224 if (now_sec
> te
->when_sec
||
225 (now_sec
== te
->when_sec
&& now_ms
>= te
->when_ms
))
230 retval
= te
->timeProc(eventLoop
, id
, te
->clientData
);
232 /* After an event is processed our time event list may
233 * no longer be the same, so we restart from head.
234 * Still we make sure to don't process events registered
235 * by event handlers itself in order to don't loop forever.
236 * To do so we saved the max ID we want to handle.
238 * FUTURE OPTIMIZATIONS:
239 * Note that this is NOT great algorithmically. Redis uses
240 * a single time event so it's not a problem but the right
241 * way to do this is to add the new elements on head, and
242 * to flag deleted elements in a special way for later
243 * deletion (putting references to the nodes to delete into
244 * another linked list). */
245 if (retval
!= AE_NOMORE
) {
246 aeAddMillisecondsToNow(retval
,&te
->when_sec
,&te
->when_ms
);
248 aeDeleteTimeEvent(eventLoop
, id
);
250 te
= eventLoop
->timeEventHead
;
258 /* Process every pending time event, then every pending file event
259 * (that may be registered by time event callbacks just processed).
260 * Without special flags the function sleeps until some file event
261 * fires, or when the next time event occurrs (if any).
263 * If flags is 0, the function does nothing and returns.
264 * if flags has AE_ALL_EVENTS set, all the kind of events are processed.
265 * if flags has AE_FILE_EVENTS set, file events are processed.
266 * if flags has AE_TIME_EVENTS set, time events are processed.
267 * if flags has AE_DONT_WAIT set the function returns ASAP until all
268 * the events that's possible to process without to wait are processed.
270 * The function returns the number of events processed. */
271 int aeProcessEvents(aeEventLoop
*eventLoop
, int flags
)
273 int processed
= 0, numevents
;
275 /* Nothing to do? return ASAP */
276 if (!(flags
& AE_TIME_EVENTS
) && !(flags
& AE_FILE_EVENTS
)) return 0;
278 /* Note that we want call select() even if there are no
279 * file events to process as long as we want to process time
280 * events, in order to sleep until the next time event is ready
282 if (eventLoop
->maxfd
!= -1 ||
283 ((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;
304 if (tvp
->tv_sec
< 0) tvp
->tv_sec
= 0;
305 if (tvp
->tv_usec
< 0) tvp
->tv_usec
= 0;
307 /* If we have to check for events but need to return
308 * ASAP because of AE_DONT_WAIT we need to se the timeout
310 if (flags
& AE_DONT_WAIT
) {
311 tv
.tv_sec
= tv
.tv_usec
= 0;
314 /* Otherwise we can block */
315 tvp
= NULL
; /* wait forever */
319 numevents
= aeApiPoll(eventLoop
, tvp
);
320 for (j
= 0; j
< numevents
; j
++) {
321 aeFileEvent
*fe
= &eventLoop
->events
[eventLoop
->fired
[j
].fd
];
322 int mask
= eventLoop
->fired
[j
].mask
;
323 int fd
= eventLoop
->fired
[j
].fd
;
325 /* note the fe->mask & mask & ... code: maybe an already processed
326 * event removed an element that fired and we still didn't
327 * processed, so we check if the event is still valid. */
328 if (fe
->mask
& mask
& AE_READABLE
)
329 fe
->rfileProc(eventLoop
,fd
,fe
->clientData
,mask
);
330 if (fe
->mask
& mask
& AE_WRITABLE
&& fe
->wfileProc
!= fe
->rfileProc
)
331 fe
->wfileProc(eventLoop
,fd
,fe
->clientData
,mask
);
332 if (fe
->mask
& mask
& AE_EXCEPTION
&&
333 fe
->efileProc
!= fe
->wfileProc
&&
334 fe
->efileProc
!= fe
->rfileProc
)
335 fe
->efileProc(eventLoop
,fd
,fe
->clientData
,mask
);
339 /* Check time events */
340 if (flags
& AE_TIME_EVENTS
)
341 processed
+= processTimeEvents(eventLoop
);
343 return processed
; /* return the number of processed file/time events */
346 /* Wait for millseconds until the given file descriptor becomes
347 * writable/readable/exception */
348 int aeWait(int fd
, int mask
, long long milliseconds
) {
350 fd_set rfds
, wfds
, efds
;
351 int retmask
= 0, retval
;
353 tv
.tv_sec
= milliseconds
/1000;
354 tv
.tv_usec
= (milliseconds%1000
)*1000;
359 if (mask
& AE_READABLE
) FD_SET(fd
,&rfds
);
360 if (mask
& AE_WRITABLE
) FD_SET(fd
,&wfds
);
361 if (mask
& AE_EXCEPTION
) FD_SET(fd
,&efds
);
362 if ((retval
= select(fd
+1, &rfds
, &wfds
, &efds
, &tv
)) > 0) {
363 if (FD_ISSET(fd
,&rfds
)) retmask
|= AE_READABLE
;
364 if (FD_ISSET(fd
,&wfds
)) retmask
|= AE_WRITABLE
;
365 if (FD_ISSET(fd
,&efds
)) retmask
|= AE_EXCEPTION
;
372 void aeMain(aeEventLoop
*eventLoop
)
375 while (!eventLoop
->stop
)
376 aeProcessEvents(eventLoop
, AE_ALL_EVENTS
);