条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待条件变量的条件成立而挂起(此时不再占用cpu);另一个线程使条件成立(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。
函数原型1. 定义条件变量
#include <pthread.h>pthread_cond_t cond_pro, cond_con;2. 初始化和销毁条件变量
#include <pthread.h>int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr); int pthread_cond_destroy(pthread_cond_t *cond); pthread_cond_init(&cond_pro, NULL);pthread_cond_init(&cond_con, NULL);pthread_cond_destroy(&cond_pro);pthread_cond_destroy(&cond_pro);3. 等待和激发条件
#include <pthread.h>int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);int pthread_cond_broadcast(pthread_cond_t *cond);int pthread_cond_signal(pthread_cond_t *cond); pthread_cond_wait(&cond_pro,&mutex); pthread_cond_broadcast(&cond_pro);pthread_cond_signal(&cond_pro); 代码 #include <stdio.h>#include <stdlib.h>#include <string.h>#include <pthread.h>#include <unistd.h>#define CELL 10#define FLORE 0int i=0; pthread_mutex_t mutex; pthread_cond_t cond_pro, cond_con; void* pro_handler(void *arg){ pthread_detach(pthread_self()); while(1) { pthread_mutex_lock(&mutex); while(i >=CELL) { pthread_cond_wait(&cond_pro,&mutex); } i++; if(i==1) { pthread_cond_signal(&cond_con); } printf("add i: %d /n", i); pthread_mutex_unlock(&mutex); sleep(rand() % 5 + 1); }}void* con_handler(void *arg){ pthread_detach(pthread_self()); while(1) { pthread_mutex_lock(&mutex); while(i <=FLORE) { pthread_cond_wait(&cond_cno,&mutex); } i--; if(i==9) { pthread_cond_signal(&cond_pro); } printf("con i: %d /n", i); pthread_mutex_unlock(&mutex); sleep(rand() % 5 + 1); }}int main(int argc, char *argv[]) // exe +num -num{ srand(getpid()); int con_cnt, pro_cnt; pro_cnt=atoi(argv[1]); con_cnt=atoi(argv[2]); pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond_pro,NULL); pthread_cond_init(&cond_con,NULL); pthread_t *arr=(pthread_t*)calloc(con_cnt + pro_cnt , sizeof(pthread_t)); int index=0; while(pro_cnt > 0) { pthread_create(arr + index, NULL, pro_handler, NULL); index++; pro_cnt--; } while(con_cnt > 0) { pthread_create(arr + index, NULL, con_handler, NULL); index++; con_cnt--; } while(1); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_pro); pthread_cond_destroy(&cond_con); return 0;} 注意无论是在生产者线程,还是在消费者线程中。标记黄色部分的判断条件必须用while。以生产者线程举例,当i>=CELL时,也就是i满时,此时执行pthread_cond_wait(&cond_cno,&mutex); 该生产者线程被挂起。必须等到消费者线程pthread_cond_signal(&cond_pro); 将其唤醒。但是消费者将其signal还不够,被挂其的生产者线程必须重新拿到锁,才可以被激活。但是,由于在消费者signal的同时,生产者并不能立即抢到锁,所以此时可能i值又改变变为大于等于10了。因此必须用while。不然可能导致i>10。
共0条 [查看全部]相关评论