pthread_cond_timedwait实例代码

本文通过一个具体的示例程序介绍了如何使用pthread_cond_timedwait函数实现基于时间的条件变量等待。该程序展示了如何设置绝对超时时间,并在超时前等待条件变量的变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数声明:int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime);

其中abstime是绝对系统时间

代码如下:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
struct node
{
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    int data;
};
int t=0;
void *thr_timer(void *arg)
{
    t++;
   
struct timespec timer;
    timer.tv_sec=time(NULL)+1;
    timer.tv_nsec=0;

    struct node *pnode=(struct node*)arg;
    pthread_mutex_lock(&(pnode->mutex));
    printf("lock\n");
    int ret;
    while(pnode->data==0)
    {
        ret=pthread_cond_timedwait(&(pnode->cond),&(pnode->mutex),&timer);
       
if(ret==ETIMEDOUT)
        {
            printf("time out\n");
            break;
        }
    }
    pthread_mutex_unlock(&(pnode->mutex));
    printf("%d time thread end\n",t);
    return ((void*)0);
}
int main()
{
    struct node *snode=(struct node*)malloc(sizeof(struct node));
    pthread_mutex_init(&(snode->mutex),NULL);
    pthread_cond_init(&(snode->cond),NULL);
    snode->data=0;
    pthread_t tid;
    pthread_create(&tid,NULL,thr_timer,(void*)snode);
    snode->data++;
    sleep(2);
    if(snode->data>0)
        pthread_cond_signal(&(snode->cond));
    snode->data=0;
    pthread_create(&tid,NULL,thr_timer,(void*)snode);
   // sleep(20);
    //snode->data++;
    //pthread_cond_signal(&(snode->cond));
    sleep(200);
    free(snode);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值