Skip to content

Commit

Permalink
Add locking to timer
Browse files Browse the repository at this point in the history
  • Loading branch information
tbodt committed Dec 18, 2017
1 parent 0767d54 commit 3c15e79
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
8 changes: 8 additions & 0 deletions util/timer.c
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
#include <stdlib.h>
#include <time.h>
#include "util/timer.h"
#include "misc.h"

struct timer *timer_new(timer_callback_t callback, void *data) {
struct timer *timer = malloc(sizeof(struct timer));
timer->callback = callback;
timer->data = data;
timer->running = false;
lock_init(timer);
return timer;
}

Expand All @@ -16,23 +18,28 @@ void timer_free(struct timer *timer) {

static void *timer_thread(void *param) {
struct timer *timer = param;
lock(timer);
while (true) {
struct timespec remaining = timespec_subtract(timer->end, timespec_now());
while (timespec_positive(remaining)) {
unlock(timer);
nanosleep(&remaining, NULL);
lock(timer);
remaining = timespec_subtract(timer->end, timespec_now());
}
timer->callback(timer->data);
if (timespec_positive(timer->interval)) {
timer->start = timespec_now();
timer->end = timespec_add(timer->start, timer->interval);
} else {
unlock(timer);
return NULL;
}
}
}

int timer_set(struct timer *timer, struct timer_spec spec, struct timer_spec *oldspec) {
lock(timer);
struct timespec now = timespec_now();
if (oldspec != NULL) {
oldspec->value = timespec_subtract(timer->end, now);
Expand All @@ -53,5 +60,6 @@ int timer_set(struct timer *timer, struct timer_spec spec, struct timer_spec *ol
timer->running = false;
}
}
unlock(timer);
return 0;
}
1 change: 1 addition & 0 deletions util/timer.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ struct timer {
pthread_t thread;
timer_callback_t callback;
void *data;
pthread_mutex_t lock;
};

struct timer *timer_new(timer_callback_t callback, void *data);
Expand Down

0 comments on commit 3c15e79

Please sign in to comment.