我想在指定的时间内运行一个循环,但现在我能想到的就是创建一个基于计时器的线程,并在它最终结束时使用一个信号来通知主函数。
要求是我正在寻求能够设置特定数量的毫秒计时器,同时感兴趣的对象在整个环境中移动。所以假设我知道速度,但没有位置反馈,我可以预测我所处的位置。(即以 5 rad/s 的速度旋转,确定我需要多少时间旋转 90 度)。
可能类似于下面的假设程序。
static sem_t timerSem;
static bool timerExp;
pthread_t th_timer;
static void timersignaldhandler()
{
sem_post(&timerSem);
}
void *th_timer(void *)
{
while(!timer_stopped){
int rc = sem_wait(&timerSem);
timer_func();
}
}
void shutdown_timer()
{
timerExp = true;
sem_post(&timerSem);
pthread_join(th_timer, 0);
}
void timer_func()
{
//sleep for x mS
//Shutdown
shutdown_timer();
sem_post(&demo_over); // signal main thread to exit
}
move()
{
//Move command
}
int main(int argc, char **argv)
{
timerExp = false;
pthread_create(&th_timer, NULL, th_timer, NULL);
while(!timerExp)
{
move();
}
}
这是理想的方法吗?我什至需要一个单独的计时器线程吗?
我不认为你需要做单独的线程。
为什么不这样做呢,这个程序会运行30秒
int t = time(NULL);
int i = 0;
while(t+30 > time(NULL)) {
++i;
// or do whatever in here
}
我是一名优秀的程序员,十分优秀!