這是我的基本代碼,現在問題是它運行幾個循環,然後給出分段錯誤。現在我知道分段錯誤是由於在內存位置非法讀/寫,但我沒有在該筆記上使用任何指針。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;
}
}
您正在創建無限多的線程。兩次迭代都是精確的。 – StoryTeller
但我得到的錯誤是1或2次函數被稱爲@StoryTeller –
不,你看到輸入後約2次得到它。線程創建可能比這更快地發生。這對你的程序來說是一個很大的錯誤。 – StoryTeller