I have a workflow that receives work from a channel. Something like that
void *worker(void *param) { while (!work_done) { read(g_workfds[0], work, sizeof(work)); do_work(work); } }
I need to implement a 1 second timer in the same thread as some work books. Here is what I mean:
void *worker(void *param) { prev_uptime = get_uptime(); while (!work_done) { // set g_workfds[0] as non-block now_uptime = get_uptime(); if (now_uptime - prev_uptime > 1) { do_book_keeping(); prev_uptime = now_uptime; } n = poll(g_workfds[0], 1000); // Wait for 1 second else timeout if (n == 0) // timed out continue; read(g_workfds[0], work, sizeof(work)); do_work(work); // This can take more than 1 second also } }
I use the system uptime, not the system time, because the system time can change while this thread is running. I was wondering if there is another better way to do this. I do not want to consider another thread. Using alarm()
not an option since it is already being used by another thread in the same process. This happens in a Linux environment.
source share