Do I need to call timer_delete to delete the timer every time?

I have used timer_create()

in the following code. It only runs the handler once every 10 seconds.

struct itimerspec itimer = { { 0, 0 }, { 10, 0 } };
struct sigevent si;

memset (&si, 0, sizeof (struct sigevent));
si.sigev_notify = SIGEV_THREAD;
si.sigev_notify_attributes = NULL;
si.sigev_notify_function = t;

if (timer_create (CLOCK_REALTIME, &si, &timer) < 0)
{
    fprintf (stderr, "[%d]: %s\n", __LINE__, strerror (errno));
    exit (errno);
}
if (timer_settime (timer, 0, &itimer, NULL) < 0)
{
    fprintf (stderr, "[%d]: %s\n", __LINE__, strerror (errno));
    exit (errno);
}

      

My question is, after 10 seconds my handler has been activated - now should I delete the timer using timer_delete()

before exiting the process? Or, since it only runs once, there is no need to explicitly delete it?

+3


source to share


1 answer


Yes, you need to explicitly remove the timer.

Take a look at the man (2) page for timer_create . In the notes section (particularly in the third note), you will see that each call timer_create

uses resources in the kernel, and the total number of timers in all processes that can be allocated by the kernel at the same time is limited.

If you don't delete your timers, they will eventually fail, and all apps that need to allocate timers may crash.



It's just like a memory leak - cleaning up the resources you are using or you will end up ending up.

The answer to your next question
In the comments below, you asked if it is ok to call timer_delete

inside a callback function. I didn't know how to answer, so I opened a question about it myself . It seems the answer might be. You can try experimenting with it and see if it works, but I would recommend against it. I've never seen any code that removes a timer from a callback, and the idea of โ€‹โ€‹freeing timer resources before the event is over makes me nervous.

Also, testing can sometimes give good results, but occasionally fails as you are dealing with asynchronous events. Also, your main program should run until the callback completes anyway (they will run in the same process, only different threads), so you can also remove the timer on your main thread right before exiting. I find this to be a safer solution and will be easier to debug.

+4


source







All Articles