2017-03-14 37 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),所以實際上在代碼中使用「指針」。