I want to build a timer for each thread, and the timer must be thread-
safe. How to do that?
My environment is Linux and Pthread.
Unfortunately, there is no way to get POSIX alarms to signal a calling
thread specifically. So you'll need to do some manual coding around it.
You can set up a thread to deal with the alarms. It blocks all signals
except that it sets up a handler for SIGALRM, then enters a sigwait()
loop.
When another thread wants to receive that alarm, it sets up a handler
for SIGUSR1 (say), and calls a function you provide that registers that
thread with your waiting thread.
When the process is sent a SIGALRM, the waiting thread returns from
sigwait(), works out which thread it should send the alarm to, and sends
a SIGUSR1 to that thread.
Of course you need to be quite careful to keep track of which thread
asked for an alarm at what time, and reset the alarm when necessary.