使用pthread_cond_timedwait把一个线程作为一个定时器使用.

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
当然可以,下面是一个使用pthread_cond_timedwait函数的示例: ```c #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <time.h> // 全局变量和互斥锁、条件变量 int count = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; // 线程函数,等待并增加count void* thread_func(void* arg) { pthread_mutex_lock(&mutex); struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += 3; // 设置等待时间为3秒 // 等待条件满足或超时 int ret = pthread_cond_timedwait(&cond, &mutex, &ts); if (ret == ETIMEDOUT) { printf("Wait timed out.\n"); } else if (ret == 0) { printf("Count is %d\n", count); count++; } else { printf("Wait failed.\n"); } pthread_mutex_unlock(&mutex); return NULL; } int main() { pthread_t thread; pthread_create(&thread, NULL, thread_func, NULL); sleep(1); // 等待子线程启动 pthread_mutex_lock(&mutex); count = 42; // 设置count的值 pthread_cond_signal(&cond); // 发送条件信号 pthread_mutex_unlock(&mutex); pthread_join(thread, NULL); return 0; } ``` 在此示例中,我们使用了pthread_cond_timedwait函数来等待条件满足或超时。主线程设置了一个初始值为42的count,并发送一个条件信号,子线程在等待条件满足后打印出当前的count值。如果超过了等待时间3秒,则子线程会打印出"Wait timed out."的消息。 希望这个示例能够帮助到你!如果你还有其他问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值