我正在尝试与多个消费者和生产者一起做一个消费者/生产者计划。我只是想做一些简单的事情,比如让生产者向共享数组添加一个随机数并让消费者将其取出。
尽管创建线程时出现错误。我看到了错误及其内容,但不知道如何解决。
我将向您展示生产者功能和主要功能,并将它们分开以便于阅读。
#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++;
}
}
这里是 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;
}
这是我得到的错误。
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 *â
如果我运行它,我会遇到分段错误谢谢。