You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.6 KiB

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <semaphore.h>
#include <time.h> /* time() */
int n=10, in=0,out=0,buffer[10];
sem_t empty,full;
sem_t p_mutex,s_mutex;
void* producer(void *arg){
int tag= pthread_self()%100;
int nextPro;
srand(time(NULL)+tag);
while(1){
nextPro = rand()%97;
sem_wait(&p_mutex);
sem_wait(&empty);
buffer[in] = nextPro;
printf("production:%d %d %d\n",nextPro,buffer[in],in);
usleep(1000*1000/20);
in = (in+1)%n;
sem_post(&full);
usleep(1000*1000/2);
sem_post(&p_mutex);
}
}
void* consumer(void *arg) {
int item;
while(1){
sem_wait(&full);
sem_wait(&s_mutex);
item = buffer[out];
sem_post(&empty);
printf("consume:%d %d\n",buffer[out],out);
out = (out+1)%n;
usleep(1000*1000/10);
sem_post(&s_mutex);
}
}
int main() {
pthread_t tid[2];
//初始有10个缓冲区
sem_init( &empty, 0,10);
sem_init( &full, 0,0);
sem_init(&p_mutex,0,1);
sem_init(&s_mutex,0,1);
for(int i=0;i<6;i++){
pthread_create(&tid[i], NULL, producer, NULL);
}
pthread_create(&tid[7], NULL, consumer, NULL);
pthread_create(&tid[8], NULL, consumer, NULL);
pthread_create(&tid[9], NULL, consumer, NULL);
pthread_create(&tid[10], NULL, consumer, NULL);
pthread_create(&tid[11], NULL, consumer, NULL);
for(int i = 0; i < 11; i++)
pthread_join(tid[i], NULL);
printf("main is over\n");
}