一、生產者消費者問題
數組
三種關係:生產者--生產者(互斥);消費者-消費者(互斥);生產者--消費者(互斥同步)
數據結構
兩個角色:生產者;消費者ide
一種生產場所:緩衝區post
二、環形隊列(緩衝區)spa
數據結構:能夠有多種,這裏選用數組,邏輯上將a[0]和a[size-1]相連構成環形隊列指針
判斷空/判斷滿:當讀指針和寫指針指向同一個區域爲空,或者滿(但不能區分空或者滿)blog
兩種方案:一、即尾結點與首結點之間至少留有一個元素的空間。 隊列
二、 添加一個計數器(信號量就是計數器因此這裏用信號量完成計數器的功能)get
三、semaphore同步
信號量就是一種計數器,其最重要的操做就是P,V操做;
P操做驚醒count--;V操做進行cont++;
P,V操做自己是原子操做!!!(即保證了互斥)
代碼:單生產者-單消費者
#include <stdio.h> #include <pthread.h> #include <semaphore.h> int round[64]; sem_t space_nums; sem_t data_nums; void *consumer(void *arg) { int index=0; while(1) { sem_wait(&data_nums); int num=round[index]; printf("%d consumer is done...%d\n",index,num); sem_post(&space_nums); index++; index%=64; sleep(1); } } void *producter(void *arg) { int index=0; while(1) { //space_nums--; sem_wait(&space_nums); int num=rand()%123; round[index]=num; printf("%d producter is done...%d\n",index,num); sem_post(&data_nums); index++; index%=64; sleep(1); } } int main() { pthread_t id1,id2; sem_init(&space_nums,0,64); sem_init(&data_nums,0,0); pthread_create(&id1,NULL,consumer,NULL); pthread_create(&id2,NULL,producter,NULL); pthread_join(id1,NULL); pthread_join(id2,NULL); sem_destroy(&space_nums); sem_destroy(&data_nums); }
代碼:多生產者-多消費者 //自己已經實現了P,V的原子操做已經實現了互斥
#include <stdio.h> #include <pthread.h> #include <semaphore.h> int round[64]; sem_t space_nums; sem_t data_nums; void *consumer(void *arg) { int index=0; while(1) { sem_wait(&data_nums); int num=round[index]; printf("%d consumer%d is done...%d\n",index,arg,num); sem_post(&space_nums); index++; index%=64; sleep(1); } } void *producter(void *arg) { int index=0; while(1) { //space_nums--; sem_wait(&space_nums); int num=rand()%123; round[index]=num; printf("%d producter%d is done...%d\n",index,arg,num); sem_post(&data_nums); index++; index%=64; sleep(1); } } int main() { pthread_t id1,id2,id3,id4; sem_init(&space_nums,0,64); sem_init(&data_nums,0,0); pthread_create(&id1,NULL,consumer,(void *)1); pthread_create(&id3,NULL,consumer,(void *)2); pthread_create(&id2,NULL,producter,(void *)1); pthread_create(&id4,NULL,producter,(void *)2); pthread_join(id1,NULL); pthread_join(id3,NULL); pthread_join(id4,NULL); pthread_join(id2,NULL); sem_destroy(&space_nums); sem_destroy(&data_nums); }