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);
Logo

更多推荐