0

I'm working on a program that would read the different lines from a file and start a thread for each one in which it would perform various operations depending on what's writter on the line, however I keep getting Segmentation Fault errors and I'm at a loss trying to solve it.

I tried to follow everything in this question thread: passing pointer char argument to function in thread

but it's still not working. The threaded function would be:

void *thread(void *arg)
{
    char *buf = arg;
    char *tok, *sp;
    //extracting transaction type
    tok = strtok_r(buf, " ", &sp);

//Branchement selon le type de transaction
            switch(tok[0]){
        ...
        }

and would be called by this part:

 void* readTranslinkedINFO(char* nomFichier){
        FILE *f;
        char buffer[100];
        pthread_t tid;

        //Opening file
        f = fopen(nomFichier, "rt");
        if (f==NULL)
            error(2, "readTrans: Erreur lors de l'ouverture du fichier.");

        //read first line
        fgets(buffer, 100, f);

        //start a thread for each line
        while(!feof(f)){
            pthread_create(&tid, NULL, thread, buffer);
            //reading next line
            fgets(buffer, 100, f);
        }
        pthread_join(tid, NULL);
        //closing file
        fclose(f);
        //Return
        return NULL;

Any help would be very much appreciated Sorry if there are still a few french words here and there Thanks

yakout
  • 782
  • 3
  • 9
  • 24

1 Answers1

1
  1. Why is “while ( !feof (file) )” always wrong?
  2. You have data race because the same address buffer is passed to all threads. You could use strdup() to pass a copy of each line to each thread and the thread function can handle free'ing it.
  3. You are not saving the thread ids, so you are only joining with the very last thread you create.
  4. Always do error check all functions that could fail (pthread_create, fgets, etc).
  5. A thread that process just one line is not going to be very effective - but I assume this is for learning/educational purpose. Otherwise, this implementation of multi-threading is counterproductive. Imagine you have a data file with a million lines. Creating a million threads is both bad and unlikely to work.
P.P
  • 117,907
  • 20
  • 175
  • 238
  • point 1 is okay because OP reads then checks feof, so no issue here. – Jean-François Fabre Oct 29 '17 at 21:45
  • It's still a bad idiom even if it works in this case. Using `fgets()` return value as the loop condition wouldn't require reading a line just before the loop and checking for `feof()` after reading a line. The linked post does a pretty job explaining why it's bad even if `feof` works as documented. – P.P Oct 29 '17 at 21:49