Cannot have expected output for producerconsumer (bounded-buffer) problem [message #1839635] |
Wed, 24 March 2021 18:06  |
Eclipse User |
|
|
|
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#define buffSize 1000
struct{
pthread_mutex_t mutex;
int buff[buffSize];
int producedCount;
int consumedCount;
}shared={PTHREAD_MUTEX_INITIALIZER};
void *produce(void *arg){
while(1){
pthread_mutex_lock(&shared.mutex);
if(shared.producedCount<buffSize){
shared.producedCount++;
*((int *)arg) += 1;
pthread_mutex_unlock(&shared.mutex);
}
else{
pthread_mutex_unlock(&shared.mutex);
return NULL;
}
}
}
void *consume(void *arg){
while(1){
pthread_mutex_lock(&shared.mutex);
if(shared.consumedCount<shared.producedCount){
shared.consumedCount++;
*((int *)arg) += 1;
pthread_mutex_unlock(&shared.mutex);
}
else{
pthread_mutex_unlock(&shared.mutex);
if (shared.consumedCount>=buffSize){
return NULL;
}
}
}
}
int main(){
int prodThreads,consThreads,i;
printf("\nEnter the no of Producers: ");fflush(stdout);
scanf("%d",&prodThreads);
printf("\nEnter the no of Consumers: ");fflush(stdout);
scanf("%d",&consThreads);
int producerArr[prodThreads],consumerArr[consThreads];
pthread_t producer[prodThreads],consumer[consThreads];
pthread_setconcurrency(prodThreads+consThreads);
for(i=0;i<prodThreads;i++){
producerArr[i]=0;
pthread_create(&producer[i],NULL,produce,&producerArr[i]);
}
for(i=0;i<consThreads;i++){
consumerArr[i]=0;
pthread_create(&consumer[i],NULL,consume,&consumerArr[i]);
}
for(i=0;i<prodThreads;i++){
pthread_join(producer[i],NULL);
printf("\nThe Producer (%d) produced: [%d] Items",i,producerArr[i]);
sleep(1);
}
printf("\n");
for(i=0;i<consThreads;i++){
pthread_join(consumer[i],NULL);
printf("\nThe Consumer (%d) Consumed: [%d] Items",i,consumerArr[i]);
sleep(1);
}
}
from www.eexploria.com/producer-consumer-problem-in-c/
I run it in another compiler it works fine.
Yet when I use the Eclipse IDE, the result always has the first item produced/consumed as 1000 and the rest being 0.
Console:
Enter the no of Producers: 3
Enter the no of Consumers: 4
The Producer (0) produced: [1000] Items
The Producer (1) produced: [0] Items
The Producer (2) produced: [0] Items
The Consumer (0) Consumed: [1000] Items
The Consumer (1) Consumed: [0] Items
The Consumer (2) Consumed: [0] Items
The Consumer (3) Consumed: [0] Items
Is there a way to modify it?
[Updated on: Wed, 24 March 2021 18:15] by Moderator
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.04544 seconds