pthred 写一个定时执行程序
时间: 2023-09-24 22:05:51 浏览: 52
可以使用pthread_create函数创建一个新的线程,在该线程中调用sleep函数进行定时等待,然后执行指定的任务。
下面是一个简单的示例代码:
```c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void *timer_thread(void *arg) {
while(1) {
// 暂停10秒
sleep(10);
// TODO: 执行定时任务
printf("定时任务已执行\n");
}
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t tid;
int ret;
// 创建定时器线程
ret = pthread_create(&tid, NULL, timer_thread, NULL);
if (ret != 0) {
printf("创建线程失败\n");
exit(EXIT_FAILURE);
}
// 等待定时器线程结束
pthread_join(tid, NULL);
return 0;
}
```
在上面的代码中,我们创建了一个名为timer_thread的线程,在该线程中使用sleep函数暂停10秒,然后执行定时任务。在主线程中,我们使用pthread_create函数创建了定时器线程,并使用pthread_join函数等待线程结束。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)