Home > Mobile >  basic usage of pthread function with return value
basic usage of pthread function with return value

Time:10-01

I am trying to create a thread that can read the number of lines in a file when called from main.c

main.c

#include <stdio.h>
#define MAX_FILE_NAME 100
#include "t_func.h"
#include <pthread.h>
int main(){
    int linecount;
    pthread_t thread_id;
    FILE *fh = fopen("/home/usr154/out.log", "r");
    pthread_create(&thread_id, NULL, count_lines,&fh);
    pthread_join(thread_id, (void **) linecount);
    printf("lines: %d \n", linecount);
}

t_func.h

#include <stdlib.h>
#include <stdio.h>
int count_lines(int *fh){
    char c;
    int count =0;
    if (fh == NULL)
        {
            printf("Could not open file %s", fh);
            return 0;
        }
    for (c = getc(fh); c != EOF; c = getc(fh))
        if (c == '\n')
            count  ;

    fclose(fh);
    return count;
}

I am facing 2 problems (or more), file pointer not being accepted and the return value not being handled, any help is much appreciated (I am new to C programming).

CodePudding user response:

  • MAX_FILE_NAME was not used.
  • Manage resource in same scope. I choose to do in main() here which in this case include fopen(), error check, and fclose()
  • Changed signature on *count_lines() to match what pthread_create() expects.
  • Changed type of c from char to int.
  • Changed behavior to take file on command line to avoid having to create the file that code expects.
  • I am getting a warning warning: cast to pointer from integer of different size for return (void *) count; with gcc -Wall -Wextra. Is there a better way to return a value? Other than global variable, pass in arg with an out parameter for the value, or allocating something in the thread.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void *count_lines(void *arg) {
    FILE *fh = (FILE *) arg;
    int c;
    int count = 0;
    while((c = getc(fh)) != EOF) {
        if(c == '\n') count  ;
    }
    return (void *) count;
}

int main(int argc, char *argv[]) {
    pthread_t thread_id;
    if(argc != 2) {
        printf("usage: %s path_of_flie\n", argv[0]);
        return 1;
    }
    FILE *fh = fopen(argv[1], "r");
    if(!fh) {
        printf("Could not open file %s", argv[1]);
        return 1;
    }
    pthread_create(&thread_id, NULL, count_lines, fh);
    int linecount;
    pthread_join(thread_id, (void **) &linecount);
    fclose(fh);
    printf("lines: %d \n", linecount);
}

and running the program on itself it returns:

lines: 32
  • Related