gpt4 book ai didi

c - 我是否需要一个单独的线程来为主程序中的 while 循环设置计时器?

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:21 25 4
gpt4 key购买 nike

我想在指定的时间内运行一个循环,但现在我能想到的就是创建一个基于计时器的线程,并在它最终结束时使用一个信号来通知主函数。

要求是我正在寻求能够设置特定数量的毫秒计时器,同时感兴趣的对象在整个环境中移动。所以假设我知道速度,但没有位置反馈,我可以预测我所处的位置。(即以 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
}

关于c - 我是否需要一个单独的线程来为主程序中的 while 循环设置计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28922046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com