这里简单的做了一个生产消费的案例,方便记忆
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#define NUM 10
static int s = 0;
static pthread_cond_t cond_add,cond_sub;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* add(void* params){
int i = 0;
for(i = 0 ; i < NUM ; i++){
pthread_mutex_lock(&mutex);
while(s > 0){
pthread_cond_wait(&cond_add, &mutex);
}
s++;
printf("生产一个\n");
pthread_cond_signal(&cond_sub);
pthread_mutex_unlock(&mutex);
}
pthread_mutex_lock(&mutex);
while(s > 0){
pthread_cond_wait(&cond_add, &mutex);
}
s = -1;
pthread_cond_signal(&cond_sub);
pthread_mutex_unlock(&mutex);
printf("生产线程结束\n");
pthread_exit(0);
}
void* sub(void* params){
while(s >= 0){
pthread_mutex_lock(&mutex);
while(s == 0){
pthread_cond_wait(&cond_sub, &mutex);
}
if(s < 0){
pthread_mutex_unlock(&mutex);
break;
}
s--;
printf("消费一个\n");
pthread_cond_signal(&cond_add);
pthread_mutex_unlock(&mutex);
}
printf("消费线程结束\n");
pthread_exit(0);
}
int main(){
pthread_t p1,p2;
void * res;
//初始化条件变量
pthread_cond_init(&cond_add, NULL);
pthread_cond_init(&cond_sub, NULL);
//创建线程
pthread_create(&p1,NULL,add,NULL);
pthread_create(&p2,NULL,sub,NULL);
//等待线程结束
pthread_join(p1, &res);
pthread_join(p2, &res);
//释放资源
pthread_cond_destroy(&cond_add);
pthread_cond_destroy(&cond_sub);
pthread_mutex_destroy(&mutex);
exit(0);
}
网友评论