生產者消費者模型 基於Posix訊號量和互斥量

2021-08-22 08:15:08 字數 2841 閱讀 4428

這種方式可以用訊號量初值來定義倉庫大小,迴圈生產和消費

生產者:

while(1)

消費者:

while(1)

**實現:

#include 

#include

#include

#include

#include

#define pro_count 3

#define com_count 3

#define bufsize 5

int buf[bufsize];//倉庫

int num=1;//產品編號

int rd_idx=1;//讀索引

int wr_idx=1;//寫索引

pthread_mutex_t mutex;//互斥

sem_t sem_full;//控制可生產的個數

sem_t sem_empty;//控制可消費的個數

void* pro(void* arg)

sleep(rand()%2);

buf[wr_idx]=(num++)%(bufsize+1);

num%=bufsize+1;

wr_idx=(wr_idx+1)%(bufsize+1);

printf("%d號生產者生產結束\n",id);

pthread_mutex_unlock(&mutex);

sem_post(&sem_empty);

}}void* com(void* arg)

int r=buf[rd_idx];

buf[rd_idx]=-1;

rd_idx=(rd_idx+1)%(bufsize+1);

sleep(rand()%2);

printf("%d號消費者消費結束%d\n",id,r);

pthread_mutex_unlock(&mutex);

sem_post(&sem_full);

}}int main()

//建立消費者執行緒

for(i=0;iint *p=(int*)malloc(sizeof(int));

*p=i+1;

pthread_create(&tid[i+pro_count],null,com,(void*)p);

} //等待

for(i=0;i//銷毀

sem_destroy(&sem_empty);

sem_destroy(&sem_full);

pthread_mutex_destroy(&mutex);

}

執行結果:

3號生產者開始生產1

buf[1]=-1<*****

buf[2]=-1

buf[3]=-1

buf[4]=-1

buf[5]=-1

3號生產者生產結束

2號生產者開始生產2

buf[1]=1

buf[2]=-1<*****

buf[3]=-1

buf[4]=-1

buf[5]=-1

2號生產者生產結束

2號生產者開始生產3

buf[1]=1

buf[2]=2

buf[3]=-1<*****

buf[4]=-1

buf[5]=-1

2號生產者生產結束

1號消費者開始消費1

buf[1]=1*****>

buf[2]=2

buf[3]=3

buf[4]=-1

buf[5]=-1

1號消費者消費結束1

3號消費者開始消費2

buf[1]=-1

buf[2]=2*****>

buf[3]=3

buf[4]=-1

buf[5]=-1

3號消費者消費結束2

3號生產者開始生產4

buf[1]=-1

buf[2]=-1

buf[3]=3

buf[4]=-1<*****

buf[5]=-1

3號生產者生產結束

3號生產者開始生產5

buf[1]=-1

buf[2]=-1

buf[3]=3

buf[4]=4

buf[5]=-1<*****

3號生產者生產結束

1號消費者開始消費3

buf[1]=-1

buf[2]=-1

buf[3]=3*****>

buf[4]=4

buf[5]=5

1號消費者消費結束3

1號消費者開始消費4

buf[1]=-1

buf[2]=-1

buf[3]=-1

buf[4]=4*****>

buf[5]=5

1號消費者消費結束4

2號消費者開始消費5

buf[1]=-1

buf[2]=-1

buf[3]=-1

buf[4]=-1

buf[5]=5*****>

2號消費者消費結束5

2號生產者開始生產0

buf[1]=-1

buf[2]=-1

buf[3]=-1

buf[4]=-1

buf[5]=-1

2號生產者生產結束

符合預期結果。。。

生產者消費者模型

1.生產者消費者問題 producer consumer 有限緩衝,多執行緒同步。生產者執行緒和消費者執行緒共享固定大小緩衝區。2.關鍵是保證生產者不會再緩衝區滿時加入資料,消費者不會在緩衝區空時消耗資料。3.解決辦法 讓生產者在緩衝區滿時休眠,等下次消費者消耗緩衝區中的資料的時候,生產者才能被喚醒...

生產者消費者模型

生產者與消費者 3,2,1 三種關係 生產者與消費者 互斥,同步 消費者與消費者 互斥 生產者與生產者 互斥 條件變數 int pthread cond destroy pthread cond t cond int pthread cond init pthread cond t restrict...

生產者消費者模型

當佇列滿時,生產者需要等待佇列有空間才能繼續往裡面放入商品,而在等待的期間內,生產者必須釋放對臨界資源 即佇列 的占用權。因為生產者如果不釋放對臨界資源的占用權,那麼消費者就無法消費佇列中的商品,就不會讓佇列有空間,那麼生產者就會一直無限等待下去。因此,一般情況下,當佇列滿時,會讓生產者交出對臨界資...