Reputation:
I am trying to do a consumer / producer program with multiple consumers and producers. Im just trying to do something simple as have a producer add a random number to a shared array and have a consumer take it out.
I am getting errors though with the thread create. I see the error and what its saying but not sure how to fix it.
I will show you the producer function and main and i will separate them for easy reading.
#define BUFFER_SIZE 30
struct sharedBuffer{
int resource[BUFFER_SIZE];
int produced, consumed;
int in;
int out;
};
struct sharedBuffer shared;
struct sharedBuffer s_instance = { in:0, out:0, };
void *producer(void *arg){
int item = 0;
int itemCount =0;
//shared.in =0;
while (1) {
item = produceItem(); //generate the random number
// while (shared.produced == BUFFER_SIZE); //spin if buffer is full
if(shared.produced == BUFFER_SIZE){
fprintf (stdout, "Producer added : %d items \n", shared.produced);
return NULL;
}
/* put new item in buffer */
shared.resource[shared.in] = item;
shared.in = (shared.in+1) % BUFFER_SIZE;
shared.resource[shared.in] = item;
fprintf (stdout, "Producer added: %d \n", item);
shared.produced++;
//item++;
itemCount++;
}
}
Here is main()
int main(int argc, char* argv[])
{
int i;
int result;
int num_producers;
int num_consumers;
pthread_attr_t attrs;
pthread_attr_init (&attrs);
//int producerArray[num_producers],consumerArray[num_consumers];
pthread_t producer[num_producers],consumer[num_consumers];
printf("Enter the number of Producers: \n");
scanf("%d", &num_producers);
printf("Enter the number of Consumers: \n");
scanf("%d", &num_consumers);
for(i=0; i< num_producers; i++)
{
//producerArray[i]=0;
//pthread_create(&producer[i],NULL, producer,&producerArray[i]);
pthread_create(&producer[i],NULL, producer,NULL);
}
for(i=0; i< num_consumers; i++)
{
//consumerArray[i]=0;
// pthread_create(&tid[i], NULL, &compute_prime, NULL);
//pthread_create(&consumer[i],NULL, consumer, &consumerArray[i]);
pthread_create(&consumer[i], NULL, consumer, NULL);
}
for(i=0;i<num_producers;i++)
{
pthread_join(producer[i],NULL);
//printf("\nThe Producer (%d) produced: [%d] Items",i,producerArray[i]);
sleep(1);
}
return 0;
}
Here is the error i am getting.
Consumer_producer2.c:125: warning: passing argument 3 of âpthread_createâ from incompatible pointer type
/usr/include/pthread.h:227: note: expected âvoid * (*)(void *)â but argument is of type âpthread_t *â
Consumer_producer2.c:133: warning: passing argument 3 of âpthread_createâ from incompatible pointer type
/usr/include/pthread.h:227: note: expected âvoid * (*)(void *)â but argument is of type âpthread_t *â
if i run it i get a Segmentation fault Thank you.
Upvotes: 0
Views: 6392
Reputation: 477522
You've defeated yourself with your naming scheme: You have both a free function called producer
and a local array called producer
. Pick better names that are unique, and you should be able to fix this.
Upvotes: 2