I am using pthread_create to create a thread that examines the amount of lines in a file, then returns the answer to the main thread. I have tried using pthread_join, and malloc() but I am new to both and must have used them improperly. If anyone knows how to pass an integer from a thread back to the main, please help. My code is below.
#include <pthread.h>
#include <stdio.h>
void *count_lines(void *arg)
{
FILE *fh= (FILE *) arg;
int num_lines=0;
char ch;
for(ch=getc(fh); ch!=EOF; ch=getc(fh))
if(ch=='\n')
num_lines=num_lines+1;
fclose(fh);
int* value = (int *)malloc(sizeof(int));
*value=10;
pthread_exit(value);
}
int main()
{
FILE *fh;
fh=fopen("data.txt", "r");
pthread_t my_thread;
pthread_create(&my_thread, NULL, count_lines, &fh);
void *retval;
pthread_join(my_thread, &retval);
int i = *((int *)retval);
free(retval);
printf("%d\n", i);
}
I am running an Ubuntu virtual machine and using Visual Studio Code if that is of any help. When I run the code above I get a "Core Dump (Segmentation Fault)" error. Again, an help is much appreciated.