生產者只有等到有空位置時才能生產數據,消費者只有等到有數據時才能取到數據
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
//用數組模擬環形隊列
int arr[8] = {0};
int i = 0;
int j = 0;
//設置信號量用來表示數組中的空位
sem_t blank;
//設置信號量用來表示數組中的數據
sem_t data;
void *product(void *arg)
{
while(1)
{
//生產者要生產必須要有空位,不然只能等待消費者取走數據之後才能生產
sem_wait(&blank);
arr[i%8] = rand()%123;
printf("生產者生產完成:%d\n", arr[i%8]);
i++;
//當生產成功時,數據量+1
sem_post(&data);
sleep(i%3);
}
}
void *consumer(void *arg)
{
while(1)
{
//消費者要消費必須有數據,不然只能等待生產者生產出數據之後才能取走
sem_wait(&data);
printf("消費者消費完成:%d\n", arr[j%8]);
j++;
//當消費成功時,空位量+1
sem_post(&blank);
sleep(j%5);
}
}
int main()
{
//最開始,有8個空位
sem_init(&blank, 0, 8);
//最開始,還沒有放入數據,數據爲0個
sem_init(&data, 0, 0);
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, &product, NULL);
pthread_create(&thread2, NULL, &consumer, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
sem_destroy(&blank);
sem_destroy(&data);
return 0;
}