user1314238
user1314238

Reputation: 389

Pthread blocking / updatable timer

I am currently using pthreads and I have a run() method in one of my threads. The run() method checks the first element of a vector for a start time and needs to do a blocking sleep until that time is reached, allowing other threads to execute. The problem is that the front element of the vector can update and I will need to reset the timer in my run() method. I am not really sure how to approach this issue. I can't use sleep since it will wait until the start time it last check which may have been updated to an earlier time.

Upvotes: 2

Views: 419

Answers (2)

johnnycrash
johnnycrash

Reputation: 5344

You can use pthread_kill() to wake a particular thread that is sleeping at sigtimedwait().

sigset_t _fSigMask; // global sigmask

We do this before creating our threads. Threads inherit their signal mask from the thread that creates them. We use SIGUSR1 to signal our threads. Other signals are available.

sigemptyset(&_fSigMask);
sigaddset(&_fSigMask, SIGUSR1);
sigaddset(&_fSigMask, SIGSEGV);

Then to sleep a thread:

int nSig;
struct timespec tmTimeout = { nSec, nNanoSec }; // from your vector of times
sigtimedwait(&fSigMask, &nSig, &tmTimeout);

Then to wake the thread, pThread, just signal it:

pthread_kill(pThread, SIGUSR1);

By the way, during our testing, sleeping and waking our threads this way was many times faster than using condition variables.

Upvotes: 1

Duck
Duck

Reputation: 27552

Whatever is updating the vector is going to need to signal the sleeping thread one way or another. There are a dozen ways to do this but two obvious ones are condition variables or just using select with a pipe or similar.

With condition variables you can used pthread_cond_timedwait with your calculated timeout value. If it times out, fine. If you get signaled you have to read the vector, recalculate the timeout, and block again.

Similarly with select() you calculate and use the timeout value from the vector and block while waiting for a timeout or some input on the pipe. Whatever is updating the vector also writes something to the pipe and the thread wakes up, recalculates, and so on...

Upvotes: 0

Related Questions