2 #if !defined(MAX_TIMERS)
3 #define MAX_TIMERS MAX_WORKER_THREADS
6 typedef int (*taction)(void *arg);
16 pthread_t threadid; /* Timer thread ID */
17 pthread_mutex_t mutex; /* Protects timer lists */
18 struct ttimer timers[MAX_TIMERS]; /* List of timers */
19 unsigned timer_count; /* Current size of timer list */
23 timer_add(struct mg_context *ctx,
39 clock_gettime(CLOCK_MONOTONIC, &now);
40 next_time += now.tv_sec;
41 next_time += now.tv_nsec * 1.0E-9;
44 pthread_mutex_lock(&ctx->timers->mutex);
45 if (ctx->timers->timer_count == MAX_TIMERS) {
48 for (u = 0; u < ctx->timers->timer_count; u++) {
49 if (ctx->timers->timers[u].time < next_time) {
50 for (v = ctx->timers->timer_count; v > u; v--) {
51 ctx->timers->timers[v] = ctx->timers->timers[v - 1];
56 ctx->timers->timers[u].time = next_time;
57 ctx->timers->timers[u].period = period;
58 ctx->timers->timers[u].action = action;
59 ctx->timers->timers[u].arg = arg;
60 ctx->timers->timer_count++;
62 pthread_mutex_unlock(&ctx->timers->mutex);
67 timer_thread_run(void *thread_func_param)
69 struct mg_context *ctx = (struct mg_context *)thread_func_param;
76 mg_set_thread_name("timer");
78 if (ctx->callbacks.init_thread) {
80 ctx->callbacks.init_thread(ctx, 2);
83 #if defined(HAVE_CLOCK_NANOSLEEP) /* Linux with librt */
85 while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &request, &request)
90 clock_gettime(CLOCK_MONOTONIC, &now);
91 d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
92 while (ctx->stop_flag == 0) {
93 pthread_mutex_lock(&ctx->timers->mutex);
94 if (ctx->timers->timer_count > 0 && d >= ctx->timers->timers[0].time) {
95 t = ctx->timers->timers[0];
96 for (u = 1; u < ctx->timers->timer_count; u++) {
97 ctx->timers->timers[u - 1] = ctx->timers->timers[u];
99 ctx->timers->timer_count--;
100 pthread_mutex_unlock(&ctx->timers->mutex);
101 re_schedule = t.action(t.arg);
102 if (re_schedule && (t.period > 0)) {
103 timer_add(ctx, t.time + t.period, t.period, 0, t.action, t.arg);
107 pthread_mutex_unlock(&ctx->timers->mutex);
110 clock_gettime(CLOCK_MONOTONIC, &now);
111 d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
117 static unsigned __stdcall timer_thread(void *thread_func_param)
119 timer_thread_run(thread_func_param);
124 timer_thread(void *thread_func_param)
126 timer_thread_run(thread_func_param);
132 timers_init(struct mg_context *ctx)
134 ctx->timers = (struct ttimers *)mg_calloc(sizeof(struct ttimers), 1);
135 (void)pthread_mutex_init(&ctx->timers->mutex, NULL);
137 /* Start timer thread */
138 mg_start_thread_with_id(timer_thread, ctx, &ctx->timers->threadid);
144 timers_exit(struct mg_context *ctx)
147 (void)pthread_mutex_destroy(&ctx->timers->mutex);
148 mg_free(ctx->timers);