Linux C多线程实现生产者消费者

时间:2024-10-22 09:04:08

今天学习了用Linux C进行线程的同步,实现类似生产者消费者的问题。下面我就来分享我的代码

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h> pthread_t tid1;
pthread_t tid2;
pthread_cond_t cond_id;
pthread_mutex_t mutex_id;
int number = 0;
int i = 0; void * thread_printA()
{
while(i<100)
{
pthread_mutex_lock(&mutex_id);
if(number<0)
{
pthread_cond_wait(&cond_id,&mutex_id);
}
number--;
printf("A");
i++; pthread_cond_signal(&cond_id);
pthread_mutex_unlock(&mutex_id);
}
} void * thread_printB()
{
while(i<100)
{
pthread_mutex_lock(&mutex_id);
if(number>=0)
{
pthread_cond_wait(&cond_id,&mutex_id);
}
number++;
printf("B");
i++;
pthread_cond_signal(&cond_id);
pthread_mutex_unlock(&mutex_id);
}
} void main()
{
pthread_create(&tid1,NULL,thread_printA,NULL);
pthread_create(&tid2,NULL,thread_printB,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
}