简体   繁体   English

Pthread阻塞/可更新计时器

[英]Pthread blocking / updatable timer

I am currently using pthreads and I have a run() method in one of my threads. 我当前正在使用pthreads,我的一个线程中有一个run()方法。 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. run()方法检查向量的第一个元素的开始时间,并且需要进行阻塞睡眠,直到达到该时间为止,从而允许其他线程执行。 The problem is that the front element of the vector can update and I will need to reset the timer in my run() method. 问题在于向量的前元素可以更新,因此我需要在run()方法中重置计时器。 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. 我无法使用sleep,因为它将一直等到上次检查的开始时间(可能已更新为更早的时间)。

You can use pthread_kill() to wake a particular thread that is sleeping at sigtimedwait(). 您可以使用pthread_kill()唤醒在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. 我们使用SIGUSR1发出线程信号。 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,只需发出信号:

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. 有十多种方法可以执行此操作,但是两个明显的方法是条件变量,或者仅在管道或类似对象上使用select。

With condition variables you can used pthread_cond_timedwait with your calculated timeout value. 通过条件变量,可以将pthread_cond_timedwait与计算出的超时值一起使用。 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. select()类似,您可以在等待超时或管道上的某些输入的同时,从向量和块中计算并使用超时值。 Whatever is updating the vector also writes something to the pipe and the thread wakes up, recalculates, and so on... 无论更新向量是什么,都会向管道中写入一些内容,并且线程将唤醒,重新计算等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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