linux在线程里面加while循环实现C语言定时器代码
时间: 2024-02-24 09:58:38 浏览: 33
可以使用Linux下的定时器API——timer_create()和timer_settime()来实现C语言定时器的功能。下面是一个简单的示例代码,使用一个线程来启动定时器,并在定时器超时时执行指定的任务。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
timer_t timer_id;
void timer_handler(int signum)
{
printf("Timer expired.\n");
}
void *timer_thread(void *arg)
{
struct sigevent sev;
struct itimerspec its;
// 创建定时器
memset(&sev, 0, sizeof(sev));
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGUSR1;
sigemptyset(&sev.sigev_value.sival_ptr);
if (timer_create(CLOCK_REALTIME, &sev, &timer_id) == -1)
{
perror("timer_create");
exit(EXIT_FAILURE);
}
// 设置定时器
its.it_value.tv_sec = 1;
its.it_value.tv_nsec = 0;
its.it_interval.tv_sec = 1;
its.it_interval.tv_nsec = 0;
if (timer_settime(timer_id, 0, &its, NULL) == -1)
{
perror("timer_settime");
exit(EXIT_FAILURE);
}
// 循环等待定时器事件
while (1)
{
sleep(1);
}
}
int main()
{
pthread_t tid;
// 注册定时器信号处理函数
signal(SIGUSR1, timer_handler);
// 创建定时器线程
if (pthread_create(&tid, NULL, timer_thread, NULL) != 0)
{
perror("pthread_create");
exit(EXIT_FAILURE);
}
// 等待定时器线程结束
if (pthread_join(tid, NULL) != 0)
{
perror("pthread_join");
exit(EXIT_FAILURE);
}
return 0;
}
```
在上面的代码中,我们创建了一个线程来启动定时器,并在定时器超时时执行指定的任务。定时器的设置和处理都在timer_thread()函数中完成,其中使用while循环来等待定时器事件的到来。在主线程中,我们调用pthread_create()函数创建了一个新线程,并在其中启动定时器。最后,我们使用pthread_join()函数等待定时器线程结束,以确保程序正常退出。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)