Search code examples
cmultithreadingpthread-join

Pthread_join Printf


I have this problem that I'm studying but I'm not understanding one part. The script is not in English so translating would be pretty tedious but the basic problem is to make a thread read a specific text file and find a specific word. Each file has its own thread and all that. The last 2 problems are making sure that various occurrences on the same file are printed together, like:

file1: line 1
file1: line 2
file2: line 1

and so on. I could solve this using a global 2d array and creating a structure to pass to the thread its "id" and the name of the txt file it has to search. I used pthread_join and it´s pretty intuitive. The problem is in the next problem, solve the same problem but without pthread_join, and with no busy waiting if possible. The problem is, if I don't use pthread_join, I can't print anything on the thread function and I wasn't expecting this? Is there a reason why this happens?

This is the code I used for solving the problem with pthread_join. Without pthread_join, using a mutex and trying to print the output on the thread function, I got no output.

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<errno.h>
#include<fcntl.h>
#include <pthread.h>
#define k 4
#define l 100

int match_line(int fd, char *str);
void *ocorre(void *);

char string[100];
int b[k][l];
int max;

struct args{
    char str[256];
    int id;
};
int main(int argc, char *argv[]){

    int i=0;
    int j=0;
    max=argc-1;

    struct args arg[max];
    pthread_t a[max];

    strcpy(string,argv[1]); //global

    for(i=0;i<max-1;i++){   //criaçao de threads
        arg[i].id=i;
        strcpy(arg[i].str,argv[i+2]);
        pthread_create(&a[i],NULL,ocorre,&arg[i]);
    }

    for(i=0;i<max-1;i++){ //join
        pthread_join(a[i],NULL);
            for(j=0;b[i][j]!=0;j++){
                printf("%s : %d\n",arg[i].str,b[i][j]);
            }
    }
}
void *ocorre(void *arg) {

    int fd;
    int j=0;
    struct args func;
    func=*(struct args*)arg;

    fd=open(func.str,O_RDONLY);
        while(1){
        b[func.id][j]=match_line(fd,string);
            if(b[func.id][j]==0) 
                break;
        j++;
    }

    return NULL;
}

This is what i did to try to solve without pthread_join. To obtain the first output i have to add sleep(1) after creating the thread


Solution

  • Returning from main terminates the process because it's roughly equivalent to calling exit. You have two choices:

    1. Make sure main doesn't return or otherwise end until all work is done, or

    2. Call phthread_exit in main rather than returning.

    Ideally, you would create all your threads as joinable and some shutdown code, that runs only after all useful work is done, arranges for the threads to terminate and joins them.