简体   繁体   中英

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.

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM