//信号量
int t = 0;
sem_t empty,full;//信号量 empty表示空的个数加一 full表示满的个数减一
pthread_mutex_t mutex; // 互斥量
void* producer(void* arg){
int* time=(int*) arg;
while(true){
sem_wait(&empty);//空的个数加一
pthread_mutex_lock(&mutex);
//add
t++;
printf("producer add 1 to %d\n", t);
pthread_mutex_unlock(&mutex);
sem_post(&full); //满的个数减一
sleep(*time);
}
}
void* customer(void* arg){
while(true){
sem_wait(&full); //满的个数减一
pthread_mutex_lock(&mutex);
//delete
t--;
printf("customer delete 1 to %d\n", t);
pthread_mutex_unlock(&mutex);
sem_post(&empty);//空的个数减一
sleep(4);
}
}
int main(){
pthread_t pthread_producer,pthread_producer_2;
pthread_t pthread_customer;
pthread_mutex_init(&mutex,NULL);
sem_init(&full,0,0);
sem_init(&empty,0,10);
int a = 2;
int b = 3;
pthread_create(&pthread_producer,NULL,producer,&a);
pthread_create(&pthread_producer_2,NULL,producer,&b);
pthread_create(&pthread_customer,NULL,customer,NULL);
pthread_join(pthread_customer,NULL);
pthread_join(pthread_producer,NULL);
pthread_join(pthread_producer_2,NULL);
return 0;
}
//条件变量
int t = 0; // 消费者减t,生产者加t
pthread_mutex_t mutex; // 互斥量
pthread_cond_t cond_full; // 非满条件变量
pthread_cond_t cond_empty; // 非空条件变量
int main(){
pthread_t producer;
pthread_t consumer;
// 初始化互斥量
pthread_mutex_init(&mutex,NULL);
// 初始化条件变量
pthread_cond_init(&cond_full,NULL);
pthread_cond_init(&cond_empty,NULL);
// 创建线程
pthread_create(
&producer, // 指明哪个线程
NULL,
producer_function, // 线程执行什么函数
NULL // 传给函数的参数
);
pthread_create(
&consumer,
NULL,
consumer_function,
NULL
);
// 等待线程结束
pthread_join(prod