// 前面一篇博客的生產者-消費者的例子是基於鏈表的,其空間可以動態分配,現在基於固定大小的環形隊列重寫這個程序:
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#define NUM 5
int queue[NUM];
/**
* semaphore變量的類型爲sem_t,sem_init()初始化一個semaphore變量,
* value參數表示可用資源的數量,pshared參數爲0表示信號量用於同一進程的線程間同步
*/
sem_t blank_number, product_number;
void *producer(void *arg)
{
static int p = 0;
while(1){
// 調用sem_wait()可以獲得資源,使semaphore的值減1,如果調用sem_wait()時semaphore的值已經是0,則掛起等待。
// 如果不希望掛起等待,可以調用sem_trywait()。
// 這裏使得blank_number的值減1,初始值是5
sem_wait(&blank_number);
queue[p] = rand()%1000;
printf("Produce %d\n", queue[p]);
p = (p+1)%NUM;
sleep(rand()%5);
// 調用sem_post()可以釋放資源,使semaphore的值加1,同時喚醒掛起等待的線程。
// 使得product_number值加1,初始值是0
sem_post(&product_number);
}
}
void *consumer(void *arg)
{
static int c = 0;
while(1){
// 使得product_number值加1,初始值是0
sem_wait(&product_number);
printf("Consume %d\n", queue[c]);
c = (c+1)%NUM;
sleep(rand()%5);
// 這裏使得blank_number的值減1,初始值是5
sem_post(&blank_number);
}
}
int main(int argc, char *argv[])
{
//刷新 console cdt下的配置,其他可以忽略
setbuf(stdout,NULL);
pthread_t pid, cid;
sem_init(&blank_number, 0, NUM);
sem_init(&product_number, 0, 0);
pthread_create(&pid, NULL, producer, NULL);
pthread_create(&cid, NULL, consumer, NULL);
pthread_join(pid, NULL);
pthread_join(cid, NULL);
sem_destroy(&blank_number);
sem_destroy(&product_number);
return 0;
}
這篇和上一篇博客的例子給出一個重要的提示:用
Condition Variable
可以實現Semaphore
。有時間用Condition Variable
實現Semaphore
,然後用自己實現的Semaphore重寫本節的程序。