分段错误 - 生产者消费者

时间:2017-03-14 14:03:46

标签: c producer-consumer producer

这是我的基本代码,现在问题是它运行了几个循环然后给出了分段错误。现在我知道分段错误是由于在内存位置非法读/写,但我没有在那个笔记上使用任何指针。

#include<stdio.h>
#include<math.h>
#include<stdbool.h>
#include<pthread.h>
#include<stdlib.h>

int counter = 0;
int BUFFER_SIZE = 5;
int buffer[] = {0};
int in = 0;
int out = 0;
void *prod(char);
void *cons(void);
bool flag = true;

void main()
{   int i, j;

    pthread_t thread1, thread2; 
    do{

            flag = true;
            i = pthread_create(&thread1, NULL, prod('i'), NULL);
            flag = true;
            j = pthread_create(&thread2, NULL, cons(), NULL);

    }while(1);
}

void* prod(char a)
{
    while (flag) {
      printf("\nCounter  = %d", counter);

while (counter == BUFFER_SIZE) {
      printf("\nBusy Waiting!!!");
} 

buffer[in] = a;
in = (in + 1) % BUFFER_SIZE;
printf("\nProducer produced an item %c!",a);
counter++;
printf("\nTotal items produced = %d",counter);

flag = false;

}
}

void* cons()
{
  char a;
  while (flag) {
    printf("\nCounter  = %d",counter);
    while (counter == 0){printf("\nBusy Waiting!!!");
  } 

  a = buffer[out];
  out = (out + 1) % BUFFER_SIZE;

  counter--;

  printf("\nTotal items remaining = %d",counter);
  flag = false;
}
}

OUPUT

3 个答案:

答案 0 :(得分:1)

您有多个严重错误:

  • 您正在永久循环中创建线程,直到程序内存不足。你想要做的只是创建一次 n 个线程,然后让主程序循环(永远?)。
  • pthread_create(&thread1, NULL, prod('i'), NULL)不正确,你在这里调用回调函数,而不是提供一个函数指针。回调的参数需要单独传递。阅读有关pthread_create
  • 的手册
  • pthreads期望一种void* func (void*)类型的函数格式。您不能使用任何其他功能格式。所以你的两个回调函数都有错误的格式。
  • 您没有对多个线程之间共享的变量使用任何形式的保护机制。您需要使用互斥锁或类似的。
  • stdio.h不一定是线程安全的,具体取决于您使用的是哪个系统和C标准版本。见stdout thread-safe in C

答案 1 :(得分:0)

您应该运行循环一次并使用pthread_join等待创建的线程。 while循环创建新线程并重写句柄(thread1thread2),这很可能是导致崩溃的原因。

答案 2 :(得分:0)

由于buffer数组,您的segfault肯定是肯定的。您正在使用最多5个位置的代码中定义大小为1及更高版本的数组。

您将其定义为:

int BUFFER_SIZE = 5;
int buffer[] = {0};

这实际上创建了一个只能容纳1个int的缓冲区(因为你只使用了一个初始化器)。

然后你以模BUFFER_SIZE为其索引:

buffer[in] = a;
in = (in + 1) % BUFFER_SIZE;

在第一次迭代后(buffer大于0时,这将溢出in,并且您正在尝试索引未分配的位置-or,更好地说,部分内存分配给buffer)。

你认为你并没有使用指针,但是在引擎盖下,你是。在C中,数组索引buffer[in]等同于*(buffer + in),所以你实际上是#34;使用指针&#34;在你的代码中。

相关问题