c - C 中的线程数组

标签 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 *â

如果我运行它,我会遇到段错误 谢谢。

最佳答案

您的命名方案打败了自己:您有一个名为 Producer 的自由函数和一个名为 Producer 的本地数组。选择更好、更独特的名称,您应该能够解决这个问题。

关于c - C 中的线程数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13111816/

相关文章:

php - 代码点火器 : create multidimensional array of result

c++ Bag Of Words聚集数组大小问题

java - 无法刷新 JFrame

java - 使用线程运行不属于事务的方法?

c - 嵌入式系统 : static or dynamic linking

c - 基本逻辑运算符问题

c - posix_memalign 的系统调用中断

c - struct allocate C 表

multithreading - 使用QTtimer安排线程?

c - 从生成过程中排除 child