This is my basic code , now the problem is that it runs for couple of loops and then gives segmentation fault. Now I know that segmentation error is due to illegal read/write at a memory location, but I haven't used any pointers on that note.
#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;
}
}
You have multiple severe bugs:
pthread_create(&thread1, NULL, prod('i'), NULL)
is incorrect, you are calling the callback function here instead of providing a function pointer to it. Arguments to the callback need to be passed separately. Read the manual about pthread_create
.void* func (void*)
. You are not allowed to use any other function format. So both of your callback functions have the wrong format.