linux 两种超时等待的实现

1. 基于信号量
1 信号量初始化

    /*信号量声明*/
    sem_t sem;

    /*信号量初始化*/
    if(sem_init(&sem, 0, 0)) 
    printf("semaphore sem intitialization failed\n");

2 超时等待:线程1

    /*超时时间宏: s*/
    #define DIAG_TIMEOUT 10
    struct timeval now;
    struct timespec out_time;

    /*开始进行超时等待*/
    gettimeofday(&now, NULL);
    out_time.tv_sec = now.tv_sec + DIAG_TIMEOUT;
    out_time.tv_nsec = now.tv_usec * 1000;
    while ((ret = sem_timedwait(&sem, &out_time)) == -1 && errno == EINTR) {
        continue; /* Restart if interrupted by handler */
    }
    if (0 != ret)
    printf("wait result timeout! \n");

3 释放:线程2

    if(条件满足)
    sem_post(&sem);

4 信号量反初始化

    sem_destroy(&sem);

2. 基于条件变量
1 条件变量初始化

    /*条件变量声明*/
    pthread_cond_t cond;
    pthread_mutex_t mutex;

    /*条件变量初始化*/
    if (pthread_mutex_init(&mutex, NULL)) {
        printf("ERROR: mutex creat failed\n");
    }
    if (pthread_cond_init(&cond, NULL)) {
        printf("ERROR: cond creat failed\n");
    }

2 超时等待:线程1

    #define PEPS_TIMEOUT 10
    struct timeval now;
    struct timespec outtime;

    /*wait the send result: successful or failure*/
    pthread_mutex_lock(&mutex);
    gettimeofday(&now, NULL);           
    outtime.tv_sec = now.tv_sec + PEPS_TIMEOUT;
    outtime.tv_nsec = now.tv_usec * 1000;
    ret = pthread_cond_timedwait(&cond, &mutex, &outtime);
    if (ret != 0) {
        printf("timeout\n");    
    }
    pthread_mutex_unlock(&mutex);

3 释放:线程2

    if (条件满足) {
        pthread_mutex_lock(&mutex);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
    }

4 条件变量反初始化

    pthread_cond_destroy(&cond);    
    pthread_mutex_destroy(&mutex);
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值