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.
63 lines
1.5 KiB
63 lines
1.5 KiB
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <pthread.h>
|
|
#include <unistd.h>
|
|
#include <sys/types.h>
|
|
#include <semaphore.h>
|
|
int n = 10, in = 0, out = 0, buffer[10];
|
|
sem_t empty, full,mutex_in,mutex_out,mutex_buf;
|
|
void *producer(void *arg)
|
|
{
|
|
int tag = pthread_self() % 100;
|
|
int nextPro;
|
|
srand(time(NULL) + tag);
|
|
while (1)
|
|
{
|
|
nextPro = rand() % 97;
|
|
sem_wait(&empty);
|
|
sem_wait(&mutex_in);
|
|
buffer[in] = nextPro;
|
|
printf("production:%d %d\n", nextPro, buffer[in]);
|
|
in = (in + 1) % n;
|
|
sem_post(&mutex_in);
|
|
sem_post(&full);
|
|
usleep(1000 * 1000 / 2);
|
|
}
|
|
}
|
|
void *consumer(void *arg)
|
|
{
|
|
int item;
|
|
while (1)
|
|
{
|
|
sem_wait(&full);
|
|
sem_wait(&mutex_out);
|
|
item = buffer[out];
|
|
sem_post(&empty);
|
|
printf("consume:%d\n", buffer[out]);
|
|
out = (out + 1) % n;
|
|
sem_post(&mutex_out);
|
|
usleep(1000 * 1000 / 10);
|
|
}
|
|
}
|
|
int main()
|
|
{
|
|
// 6个生产者和6个消费者
|
|
pthread_t tid[12];
|
|
//初始有10个缓冲区
|
|
sem_init(&empty, 0, 10);
|
|
sem_init(&full, 0, 0);
|
|
sem_init(&mutex_in, 0, 1);
|
|
sem_init(&mutex_out, 0, 1);
|
|
for (size_t i = 0; i < 6; i++)
|
|
{
|
|
pthread_create(&tid[0], NULL, producer, NULL);
|
|
}
|
|
for (size_t i = 6; i < 12; i++)
|
|
{
|
|
pthread_create(&tid[i], NULL, consumer, NULL);
|
|
}
|
|
|
|
for (int i = 0; i < 7; i++)
|
|
pthread_join(tid[i], NULL);
|
|
printf("main is over\n");
|
|
} |