2017-03-14 36 views
-1

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

#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

您正在创建无限多的线程。两次迭代都是精确的。 – StoryTeller

+0

但我得到的错误是1或2次函数被称为@StoryTeller –

+0

不,你看到输入后约2次得到它。线程创建可能比这更快地发生。这对你的程序来说是一个很大的错误。 – StoryTeller

回答

1

您有多个严重错误:

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

谢谢!明白了我没有正确使用函数格式! –

+0

@GunjanRaval请注意,您需要解决以上问题_all_。这些并不是一些次要的挑剔,但它们都是严重的错误。 – Lundin

0

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

+0

但我希望这些线程无限运行,那我能做什么? –

+0

@GunjanRaval在线程内运行无限函数。 –

+0

重写'pthread_t'变量是没有问题的,它只是某种识别线程的整数。真正的问题是'pthread_create(..)'中的函数调用。 – mch

0

由于buffer阵列,您的段错误大多确定。您正在使用最多5个位置的代码中定义大小为1的数组。

您将其定义为:

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

这实际上创建了一个缓冲区,只能容纳1个INT(因为你使用的是初始只有一个值)。

然后你再编入索引模BUFFER_SIZE

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

而且第一次迭代后,将溢出buffer(当in大于0,和你想的索引未分配 - 或位置,更好地说,分配给buffer的部分内存)。

你认为你不是使用指针,而是在引擎盖下,你是。在C中,数组索引buffer[in]相当于*(buffer + in),所以实际上在代码中使用“指针”。