linux线程同步:互斥量和条件变量的使用

来源:互联网 发布:程序员笔记本电脑 编辑:程序博客网 时间:2024/04/28 07:01

线程B等待线程A更改RS422_ack_status状态后调用pthread_cond_signal()通知线程B,否则线程B调用pthread_cond_timedwait()进行阻塞,直至收到条件变量通知或等待时间超时。

互斥量和条件变量初始化:

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;int pthread_s;

线程A:

pthread_s=pthread_mutex_lock(&mtx);if(pthread_s!=0){    perror("prhread_mutex_lock");}rs422_present_status->RS422_ack_status = RS422_RECEIVE_ACK;pthread_s=pthread_mutex_unlock(&mtx);if(pthread_s!=0){    perror("prhread_mutex_unlock");}pthread_s=pthread_cond_signal(&cond);if(pthread_s!=0){    perror("pthread_cond_signal");}

线程B:

pthread_s=pthread_mutex_lock(&mtx);if(pthread_s!=0){    perror("pthread_mutex_lock");}while(rs422_present_status>RS422_ack_status!=RS422_RECEIVE_ACK){    if(clock_gettime(CLOCK_REALTIME,&delay) == -1){        perror("clock_gettime");        exit(1);    }    delay.tv_sec +=  5;    pthread_s=pthread_cond_timedwait(&cond,&mtx,&delay);    if(pthread_s==ETIMEDOUT){        printf("\nrs422: pthread_cond_timedwait time out\n");        break;    }}pthread_s=pthread_mutex_unlock(&mtx);if(pthread_s!=0){    perror("pthread_mutex_unlock");}

线程B阻塞过程说明:
这里写图片描述

pthread_cond_timedwait()置于while中的原因如下:
这里写图片描述

说明:

int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)

两个函数使用大致相同,将阻塞一线程直至收到条件变量cond的通知。
函数会自动执行对互斥量的解锁和加锁动作。
这里写图片描述

原创粉丝点击