C中的线程数组

时间:2012-10-28 18:41:21

标签: c arrays multithreading pthreads

我正在尝试与多个消费者和生产者一起开展消费者/生产者计划。我只是想做一些简单的事情,因为生产者将一个随机数添加到共享数组并让消费者将其取出。

虽然线程创建我遇到了错误。我看到错误及其说法但不确定如何修复它。

我将向您展示制作人的功能和主要内容,我会将它们分开以方便阅读。

#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 *â

如果我运行它我会得到分段错误 谢谢。

1 个答案:

答案 0 :(得分:2)

您已经使用命名方案打败了自己:您既有一个名为producer的免费函数,又有一个名为producer的本地数组。选择更好的独特名称,你应该能够解决这个问题。