Jim Tcl
Check-in [43fab94694]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:eventloop: support sub-millisecond timer resolution

Timeouts may now be specified in fractions of milliseconds. e.g. after 0.5

This can be useful on faster systems where 1ms resolution is too coarse.

Also, use clock_gettime(CLOCK_MONOTONIC_RAW) for timers, if available. This clock is insensitive to system clock changes and ntp adjustments.

Signed-off-by: Steve Bennett <steveb@workware.net.au>

Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 43fab946949a099e5379f77a70e35fa3884329d9
User & Date: steveb@workware.net.au 2017-10-15 21:00:20
Context
2017-10-15
21:03
eventloop: remove leftover debugging

Signed-off-by: Steve Bennett <steveb@workware.net.au> check-in: 6dad0537c9 user: steveb@workware.net.au tags: trunk

21:00
eventloop: support sub-millisecond timer resolution

Timeouts may now be specified in fractions of milliseconds. e.g. after 0.5

This can be useful on faster systems where 1ms resolution is too coarse.

Also, use clock_gettime(CLOCK_MONOTONIC_RAW) for timers, if available. This clock is insensitive to system clock changes and ntp adjustments.

Signed-off-by: Steve Bennett <steveb@workware.net.au> check-in: 43fab94694 user: steveb@workware.net.au tags: trunk

20:57
aio tempname: Fix a crash when the template is invalid

Signed-off-by: Steve Bennett <steveb@workware.net.au> check-in: 4d750fab2d user: steveb@workware.net.au tags: trunk

Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to auto.def.

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
}

cc-check-functions ualarm lstat fork vfork system select execvpe
cc-check-functions geteuid mkstemp realpath isatty
cc-check-functions regcomp waitpid sigaction sys_signame sys_siglist isascii
cc-check-functions syslog opendir readlink sleep usleep pipe getaddrinfo utimes
cc-check-functions shutdown socketpair isinf isnan link symlink fsync dup umask
cc-check-functions localtime gmtime strptime timegm

if {[cc-check-function-in-lib backtrace execinfo]} {
    define-append LDLIBS [get-define lib_backtrace]
}

if {[cc-check-functions sysinfo]} {
    cc-with {-includes sys/sysinfo.h} {







|







110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
}

cc-check-functions ualarm lstat fork vfork system select execvpe
cc-check-functions geteuid mkstemp realpath isatty
cc-check-functions regcomp waitpid sigaction sys_signame sys_siglist isascii
cc-check-functions syslog opendir readlink sleep usleep pipe getaddrinfo utimes
cc-check-functions shutdown socketpair isinf isnan link symlink fsync dup umask
cc-check-functions localtime gmtime strptime timegm clock_gettime

if {[cc-check-function-in-lib backtrace execinfo]} {
    define-append LDLIBS [get-define lib_backtrace]
}

if {[cc-check-functions sysinfo]} {
    cc-with {-includes sys/sysinfo.h} {

Changes to jim-eventloop.c.

50
51
52
53
54
55
56

57
58
59
60
61
62

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
..
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
...
185
186
187
188
189
190
191
192
193
194
195

196
197









198
199



200
201
202
203
204
205
206
207
208
209


210
211
212
213
214
215
216
217
218
219
220
...
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
...
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
...
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
...
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
...
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
...
612
613
614
615
616
617
618

619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
...
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

#if defined(__MINGW32__)
#include <windows.h>
#include <winsock.h>

#define msleep Sleep
#else
#include <sys/types.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif


#ifndef HAVE_USLEEP
/* XXX: Implement this in terms of select() or nanosleep() */
#define msleep(MS) sleep((MS) / 1000)
#warning "sub-second sleep not supported"
#else
#define msleep(MS) sleep((MS) / 1000); usleep(((MS) % 1000) * 1000);
#endif
#endif

/* --- */

/* File event structure */
typedef struct Jim_FileEvent
{
................................................................................
    struct Jim_FileEvent *next;
} Jim_FileEvent;

/* Time event structure */
typedef struct Jim_TimeEvent
{
    jim_wide id;                /* time event identifier. */
    long initialms;             /* initial relative timer value */
    jim_wide when;              /* milliseconds */
    Jim_TimeProc *timeProc;
    Jim_EventFinalizerProc *finalizerProc;
    void *clientData;
    struct Jim_TimeEvent *next;
} Jim_TimeEvent;

/* Per-interp stucture containing the state of the event loop */
................................................................................
            continue;
        }
        prev = fe;
    }
}

/**
 * Returns the time since interp creation in milliseconds.
 */
static jim_wide JimGetTime(Jim_EventLoop *eventLoop)
{

    struct timeval tv;










    gettimeofday(&tv, NULL);




    return (jim_wide)(tv.tv_sec - eventLoop->timeBase) * 1000 + tv.tv_usec / 1000;
}

jim_wide Jim_CreateTimeHandler(Jim_Interp *interp, jim_wide milliseconds,
    Jim_TimeProc * proc, void *clientData, Jim_EventFinalizerProc * finalizerProc)
{
    Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
    jim_wide id = ++eventLoop->timeEventNextId;
    Jim_TimeEvent *te, *e, *prev;



    te = Jim_Alloc(sizeof(*te));
    te->id = id;
    te->initialms = milliseconds;
    te->when = JimGetTime(eventLoop) + milliseconds;
    te->timeProc = proc;
    te->finalizerProc = finalizerProc;
    te->clientData = clientData;

    /* Add to the appropriate place in the list */
    prev = NULL;
    for (e = eventLoop->timeEventHead; e; e = e->next) {
................................................................................
        return -2;              /* wrong event ID */
    }

    te = Jim_RemoveTimeHandler(eventLoop, id);
    if (te) {
        jim_wide remain;

        remain = te->when - JimGetTime(eventLoop);
        remain = (remain < 0) ? 0 : remain;

        Jim_FreeTimeHandler(interp, te);
        return remain;
    }
    return -1;                  /* NO event with the specified ID found */
}
................................................................................
 * the events that are possible to process without waiting are processed.
 *
 * Returns the number of events processed or -1 if
 * there are no matching handlers, or -2 on error.
 */
int Jim_ProcessEvents(Jim_Interp *interp, int flags)
{
    jim_wide sleep_ms = -1;
    int processed = 0;
    Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
    Jim_FileEvent *fe = eventLoop->fileEventHead;
    Jim_TimeEvent *te;
    jim_wide maxId;

    if ((flags & JIM_FILE_EVENTS) == 0 || fe == NULL) {
................................................................................
    /* Note that we want call select() even if there are no
     * file events to process as long as we want to process time
     * events, in order to sleep until the next time event is ready
     * to fire. */

    if (flags & JIM_DONT_WAIT) {
        /* Wait no time */
        sleep_ms = 0;
    }
    else if (flags & JIM_TIME_EVENTS) {
        /* The nearest timer is always at the head of the list */
        if (eventLoop->timeEventHead) {
            Jim_TimeEvent *shortest = eventLoop->timeEventHead;

            /* Calculate the time missing for the nearest
             * timer to fire. */
            sleep_ms = shortest->when - JimGetTime(eventLoop);
            if (sleep_ms < 0) {
                sleep_ms = 0;
            }
        }
        else {
            /* Wait forever */
            sleep_ms = -1;
        }
    }

#ifdef HAVE_SELECT
    if (flags & JIM_FILE_EVENTS) {
        int retval;
        struct timeval tv, *tvp = NULL;
................................................................................
            if (fe->mask & JIM_EVENT_EXCEPTION)
                FD_SET(fe->fd, &efds);
            if (maxfd < fe->fd)
                maxfd = fe->fd;
            fe = fe->next;
        }

        if (sleep_ms >= 0) {
            tvp = &tv;
            tvp->tv_sec = sleep_ms / 1000;
            tvp->tv_usec = 1000 * (sleep_ms % 1000);
        }

        retval = select(maxfd + 1, &rfds, &wfds, &efds, tvp);

        if (retval < 0) {
            if (errno == EINVAL) {
                /* This can happen on mingw32 if a non-socket filehandle is passed */
................................................................................
                else {
                    fe = fe->next;
                }
            }
        }
    }
#else
    if (sleep_ms > 0) {
        msleep(sleep_ms);
    }
#endif

    /* Check time events */
    te = eventLoop->timeEventHead;
    maxId = eventLoop->timeEventNextId;
    while (te) {
        jim_wide id;

        if (te->id > maxId) {
            te = te->next;
            continue;
        }
        if (JimGetTime(eventLoop) >= te->when) {
            id = te->id;
            /* Remove from the list before executing */
            Jim_RemoveTimeHandler(eventLoop, id);
            te->timeProc(interp, te->clientData);
            /* After an event is processed our time event list may
             * no longer be the same, so we restart from head.
             * Still we make sure to don't process events registered
................................................................................

    Jim_DecrRefCount(interp, objPtr);
}

static int JimELAfterCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
    Jim_EventLoop *eventLoop = Jim_CmdPrivData(interp);

    jim_wide ms = 0, id;
    Jim_Obj *objPtr, *idObjPtr;
    static const char * const options[] = {
        "cancel", "info", "idle", NULL
    };
    enum
    { AFTER_CANCEL, AFTER_INFO, AFTER_IDLE, AFTER_RESTART, AFTER_EXPIRE, AFTER_CREATE };
    int option = AFTER_CREATE;

    if (argc < 2) {
        Jim_WrongNumArgs(interp, 1, argv, "option ?arg ...?");
        return JIM_ERR;
    }
    if (Jim_GetWide(interp, argv[1], &ms) != JIM_OK) {
        if (Jim_GetEnum(interp, argv[1], options, &option, "argument", JIM_ERRMSG) != JIM_OK) {
            return JIM_ERR;
        }
        Jim_SetEmptyResult(interp);
    }
    else if (argc == 2) {
        /* Simply a sleep */
        msleep(ms);
        return JIM_OK;
    }

    switch (option) {
        case AFTER_IDLE:
            if (argc < 3) {
                Jim_WrongNumArgs(interp, 2, argv, "script ?script ...?");
                return JIM_ERR;
            }
            /* fall through */
        case AFTER_CREATE: {
            Jim_Obj *scriptObj = Jim_ConcatObj(interp, argc - 2, argv + 2);
            Jim_IncrRefCount(scriptObj);
            id = Jim_CreateTimeHandler(interp, ms, JimAfterTimeHandler, scriptObj,
                JimAfterTimeEventFinalizer);
            objPtr = Jim_NewStringObj(interp, NULL, 0);
            Jim_AppendString(interp, objPtr, "after#", -1);
            idObjPtr = Jim_NewIntObj(interp, id);
            Jim_IncrRefCount(idObjPtr);
            Jim_AppendObj(interp, objPtr, idObjPtr);
            Jim_DecrRefCount(interp, idObjPtr);
................................................................................
            else if (argc == 3) {
                id = JimParseAfterId(argv[2]);
                if (id >= 0) {
                    Jim_TimeEvent *e = JimFindTimeHandlerById(eventLoop, id);
                    if (e && e->timeProc == JimAfterTimeHandler) {
                        Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
                        Jim_ListAppendElement(interp, listObj, e->clientData);
                        Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, e->initialms ? "timer" : "idle", -1));
                        Jim_SetResult(interp, listObj);
                        return JIM_OK;
                    }
                }
                Jim_SetResultFormatted(interp, "event \"%#s\" doesn't exist", argv[2]);
                return JIM_ERR;
            }







>
|





>



|

<
<
<







 







|
|







 







|

|

>


>
>
>
>
>
>
>
>
>
|

>
>
>
|


|






>
>


|
|







 







|







 







|







 







|








|
|
|




|







 







|

|
|







 







|
|













|







 







>
|












|







|













|







 







|







50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69



70
71
72
73
74
75
76
..
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
...
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
...
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
...
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
...
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
...
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
...
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
...
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
...
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

#if defined(__MINGW32__)
#include <windows.h>
#include <winsock.h>
#define usleep(US) Sleep((US) / 1000)
#define HAVE_USLEEP
#else
#include <sys/types.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#endif

#ifndef HAVE_USLEEP
/* XXX: Implement this in terms of select() or nanosleep() */
#define usleep(US) sleep((US) / 1000000)
#warning "sub-second sleep not supported"



#endif

/* --- */

/* File event structure */
typedef struct Jim_FileEvent
{
................................................................................
    struct Jim_FileEvent *next;
} Jim_FileEvent;

/* Time event structure */
typedef struct Jim_TimeEvent
{
    jim_wide id;                /* time event identifier. */
    jim_wide initialus;         /* initial relative timer value in microseconds */
    jim_wide when;              /* microseconds */
    Jim_TimeProc *timeProc;
    Jim_EventFinalizerProc *finalizerProc;
    void *clientData;
    struct Jim_TimeEvent *next;
} Jim_TimeEvent;

/* Per-interp stucture containing the state of the event loop */
................................................................................
            continue;
        }
        prev = fe;
    }
}

/**
 * Returns the time since interp creation in microseconds.
 */
static jim_wide JimGetTimeUsec(Jim_EventLoop *eventLoop)
{
    long long now;
    struct timeval tv;

#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC_RAW)
    struct timespec ts;

    if (clock_gettime(CLOCK_MONOTONIC_RAW, &ts) == 0) {
        now = ts.tv_sec * 1000000LL + ts.tv_nsec / 1000;
    }
    else
#endif
    {
        gettimeofday(&tv, NULL);

        now = tv.tv_sec * 1000000LL + tv.tv_usec;
    }

    return now - eventLoop->timeBase;
}

jim_wide Jim_CreateTimeHandler(Jim_Interp *interp, jim_wide us,
    Jim_TimeProc * proc, void *clientData, Jim_EventFinalizerProc * finalizerProc)
{
    Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
    jim_wide id = ++eventLoop->timeEventNextId;
    Jim_TimeEvent *te, *e, *prev;

    printf("Create time handler, us=%lld, now=%lld\n", us, JimGetTimeUsec(eventLoop));

    te = Jim_Alloc(sizeof(*te));
    te->id = id;
    te->initialus = us;
    te->when = JimGetTimeUsec(eventLoop) + us;
    te->timeProc = proc;
    te->finalizerProc = finalizerProc;
    te->clientData = clientData;

    /* Add to the appropriate place in the list */
    prev = NULL;
    for (e = eventLoop->timeEventHead; e; e = e->next) {
................................................................................
        return -2;              /* wrong event ID */
    }

    te = Jim_RemoveTimeHandler(eventLoop, id);
    if (te) {
        jim_wide remain;

        remain = te->when - JimGetTimeUsec(eventLoop);
        remain = (remain < 0) ? 0 : remain;

        Jim_FreeTimeHandler(interp, te);
        return remain;
    }
    return -1;                  /* NO event with the specified ID found */
}
................................................................................
 * the events that are possible to process without waiting are processed.
 *
 * Returns the number of events processed or -1 if
 * there are no matching handlers, or -2 on error.
 */
int Jim_ProcessEvents(Jim_Interp *interp, int flags)
{
    jim_wide sleep_us = -1;
    int processed = 0;
    Jim_EventLoop *eventLoop = Jim_GetAssocData(interp, "eventloop");
    Jim_FileEvent *fe = eventLoop->fileEventHead;
    Jim_TimeEvent *te;
    jim_wide maxId;

    if ((flags & JIM_FILE_EVENTS) == 0 || fe == NULL) {
................................................................................
    /* Note that we want call select() even if there are no
     * file events to process as long as we want to process time
     * events, in order to sleep until the next time event is ready
     * to fire. */

    if (flags & JIM_DONT_WAIT) {
        /* Wait no time */
        sleep_us = 0;
    }
    else if (flags & JIM_TIME_EVENTS) {
        /* The nearest timer is always at the head of the list */
        if (eventLoop->timeEventHead) {
            Jim_TimeEvent *shortest = eventLoop->timeEventHead;

            /* Calculate the time missing for the nearest
             * timer to fire. */
            sleep_us = shortest->when - JimGetTimeUsec(eventLoop);
            if (sleep_us < 0) {
                sleep_us = 0;
            }
        }
        else {
            /* Wait forever */
            sleep_us = -1;
        }
    }

#ifdef HAVE_SELECT
    if (flags & JIM_FILE_EVENTS) {
        int retval;
        struct timeval tv, *tvp = NULL;
................................................................................
            if (fe->mask & JIM_EVENT_EXCEPTION)
                FD_SET(fe->fd, &efds);
            if (maxfd < fe->fd)
                maxfd = fe->fd;
            fe = fe->next;
        }

        if (sleep_us >= 0) {
            tvp = &tv;
            tvp->tv_sec = sleep_us / 1000000;
            tvp->tv_usec = sleep_us % 1000000;
        }

        retval = select(maxfd + 1, &rfds, &wfds, &efds, tvp);

        if (retval < 0) {
            if (errno == EINVAL) {
                /* This can happen on mingw32 if a non-socket filehandle is passed */
................................................................................
                else {
                    fe = fe->next;
                }
            }
        }
    }
#else
    if (sleep_us > 0) {
        usleep(sleep_us);
    }
#endif

    /* Check time events */
    te = eventLoop->timeEventHead;
    maxId = eventLoop->timeEventNextId;
    while (te) {
        jim_wide id;

        if (te->id > maxId) {
            te = te->next;
            continue;
        }
        if (JimGetTimeUsec(eventLoop) >= te->when) {
            id = te->id;
            /* Remove from the list before executing */
            Jim_RemoveTimeHandler(eventLoop, id);
            te->timeProc(interp, te->clientData);
            /* After an event is processed our time event list may
             * no longer be the same, so we restart from head.
             * Still we make sure to don't process events registered
................................................................................

    Jim_DecrRefCount(interp, objPtr);
}

static int JimELAfterCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{
    Jim_EventLoop *eventLoop = Jim_CmdPrivData(interp);
    double ms;
    jim_wide id;
    Jim_Obj *objPtr, *idObjPtr;
    static const char * const options[] = {
        "cancel", "info", "idle", NULL
    };
    enum
    { AFTER_CANCEL, AFTER_INFO, AFTER_IDLE, AFTER_RESTART, AFTER_EXPIRE, AFTER_CREATE };
    int option = AFTER_CREATE;

    if (argc < 2) {
        Jim_WrongNumArgs(interp, 1, argv, "option ?arg ...?");
        return JIM_ERR;
    }
    if (Jim_GetDouble(interp, argv[1], &ms) != JIM_OK) {
        if (Jim_GetEnum(interp, argv[1], options, &option, "argument", JIM_ERRMSG) != JIM_OK) {
            return JIM_ERR;
        }
        Jim_SetEmptyResult(interp);
    }
    else if (argc == 2) {
        /* Simply a sleep */
        usleep(ms * 1000);
        return JIM_OK;
    }

    switch (option) {
        case AFTER_IDLE:
            if (argc < 3) {
                Jim_WrongNumArgs(interp, 2, argv, "script ?script ...?");
                return JIM_ERR;
            }
            /* fall through */
        case AFTER_CREATE: {
            Jim_Obj *scriptObj = Jim_ConcatObj(interp, argc - 2, argv + 2);
            Jim_IncrRefCount(scriptObj);
            id = Jim_CreateTimeHandler(interp, (jim_wide)(ms * 1000), JimAfterTimeHandler, scriptObj,
                JimAfterTimeEventFinalizer);
            objPtr = Jim_NewStringObj(interp, NULL, 0);
            Jim_AppendString(interp, objPtr, "after#", -1);
            idObjPtr = Jim_NewIntObj(interp, id);
            Jim_IncrRefCount(idObjPtr);
            Jim_AppendObj(interp, objPtr, idObjPtr);
            Jim_DecrRefCount(interp, idObjPtr);
................................................................................
            else if (argc == 3) {
                id = JimParseAfterId(argv[2]);
                if (id >= 0) {
                    Jim_TimeEvent *e = JimFindTimeHandlerById(eventLoop, id);
                    if (e && e->timeProc == JimAfterTimeHandler) {
                        Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
                        Jim_ListAppendElement(interp, listObj, e->clientData);
                        Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, e->initialus ? "timer" : "idle", -1));
                        Jim_SetResult(interp, listObj);
                        return JIM_OK;
                    }
                }
                Jim_SetResultFormatted(interp, "event \"%#s\" doesn't exist", argv[2]);
                return JIM_ERR;
            }