0

My program creates some pthreads in a for loop that do some work, then waits for them to finish in another for loop using pthread_join and then it is supposed to show some output. The problem is that the program doesn't get passed the pthread_join loop, I've stepped through the code with a debugger and it seems that at the second iterration of the loop the program just terminates with exit code 0.

for(i = 1; i <= n_cust; i++){
    ids[i]= (int) i;
    int rc = pthread_create(&thread_ids[i], NULL, &thread_transaction, 
(void *) (&ids[i]));

    if (rc != 0) { //no error, all threads are created and print a result
        printf("ERROR: return code from pthread_create() is %d\n", rc);
        exit(-1);
    }
}

for(j=0; j < n_cust; j++) {
    if(thread_ids[j] != null){
        int rc = pthread_join(thread_ids[j], NULL);

        if (rc != 0) {//program terminates before being able to check rc
            printf("ERROR: return code from pthread_join() is %d\n", rc);
            exit(-1);
        }
    }
}

printf("SEAT ARRANGEMENT: \n");

for(y=0; y<Nseat;y++){
    printf("Seat %d / Costumer %d, ", y, seats_array[y]);
}

When i printed the value that pthread_join returns, at first I got 3 that means that a thread is null, but later I tried checking if the current thread is null before joining it and then the program just stops with exit code 0, before being able to print the rc variable. The threads seems to be doing their work correctly, since all of them print the excpected outputs. Also I don't know if this is helpful but I am building the program in windows with the windows pthread library for convenience, although I am supposed to do it in linux, or at least make sure that it works in a virtual machine. If you find it neccessary i can provide all the code of the function that gets passed in the thread. Thanks in advance.

Petros21
  • 45
  • 7
  • 2
    You loops and array indexes, are you *sure* about them? Do your arrays (like e.g. `ids`) have at least `n_cust + 1` elements? Don't forget that array indexes are *zero* based, so an array of `n_cust` elements have indexes from `0` to `n_cust - 1` (inclusive). And it seems you do it differently between the two loops (the first is one-based, the second is zero-based)? Could this be the source of your problems? – Some programmer dude Apr 11 '19 at 12:19
  • By the way, what is `null`? There's no such standard keyword (or macro) in C. Remember that C doesn't really have "null" values. – Some programmer dude Apr 11 '19 at 12:40
  • Sorry it is not null but NULL and i guess is defined in a header that i use. Also, good point I changed the first loop to start from 1 because I wanted the IDs to start with 1 and I forgot to change the second loop. This could be the problem, although I think that the check thread_ids[j] != NULL should ignore the empty position In the thread array. When i get the chance to test it, I will share. – Petros21 Apr 11 '19 at 14:14

0 Answers0