#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#include <cstdlib>
sem_t epty_sem;
sem_t ful_sem;
int buf[5] = {0};
void* productor(void* arg)
{
//srand(time(NULL));
static int i = 0;
while (1)
{
sem_wait(&epty_sem);
buf[i] = rand() % 10;
printf("product value %d\n", buf[i]);
i = (i + 1) % (sizeof(buf) / sizeof(buf[0]));
sem_post(&ful_sem);
sleep(1);
}
}
void* consumer(void* arg)
{
static int i = 0;
while (1)
{
sem_wait(&ful_sem);
printf("consume value %d\n", buf[i]);
i = (i + 1) % (sizeof(buf) / sizeof(buf[0]));
sem_post(&epty_sem);
sleep(3);
}
}
int main()
{
sem_init(&epty_sem, 0, 5);
sem_init(&ful_sem, 0, 0);
pthread_t potr_t;
pthread_t csmr_t;
pthread_create(&potr_t, NULL, productor, NULL);
pthread_create(&csmr_t, NULL, consumer, NULL);
pthread_join(potr_t, NULL);
pthread_join(csmr_t, NULL);
return 0;
}
//
// Created by helianhaodong on 2021/9/3.
//
#include <stdio.h>
#include <unistd.h>
#include <cstdlib>
#include <pthread.h>
#include <semaphore.h>
sem_t emptySem;
sem_t fullSem;
int buffer[5] = {0};
void* productorFunc(void* arg)
{
static int i = 0;
while (1)
{
sem_wait(&emptySem);
buffer[i] = rand() % 10;
printf("product value %d\n", buffer[i]);
i = (i + 1) % (sizeof(buffer) / sizeof(buffer[0]));
sem_post(&fullSem);
sleep(1);
}
}
void* consumerFunc(void* arg)
{
static int i = 0;
while (1)
{
sem_wait(&fullSem);
printf("consume value %d\n", buffer[i]);
i = (i + 1) % (sizeof(buffer) / sizeof(buffer[0]));
sem_post(&emptySem);
sleep(3);
}
}
int main()
{
sem_init(&emptySem, 0, 5);
sem_init(&fullSem, 0, 0);
pthread_t productorThread;
pthread_t consumerThread;
pthread_create(&productorThread, NULL, productorFunc, NULL);
pthread_create(&consumerThread, NULL, consumerFunc, NULL);
pthread_join(productorThread, NULL);
pthread_join(consumerThread, NULL);
return 0;
}