How do I safely delete a posix timer in c++?

The classes I'm writing contain posix timers and the handlers to those timers.

How do I safely delete the class? If the handlers fire and see that the class is deleted it segfaults.

Adding a mutex leads to a deadlock - so I wondered if there was any resources about using posix timers in a c++ class safely in a multithreaded environment.


Solution 1:

Store the timer IDs as private members of your class, never return the ID, but always wrap calls that use them in your class’ methods, and in your destructor, call timer_delete() (http://pubs.opengroup.org/onlinepubs/9699919799/functions/timer_delete.html). This way, no code can hold a timer ID that has become invalid. In short, Law of Demeter.

Your reference to deadlock implies that the problem is thread synchronization, so a shared_ptr might be the way to go. This will delete the class object only when the last reference to it is deleted. You might try some other approach, such as synchronizing your threads behind a barrier or condition variable, and deleting only when you know that every thread holding a reference to the object is currently waiting, or a reader-writer lock.