Domanda

I just wrote the following code to understand better how Threads work:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

int globalVariable = 1;
void *myfunc (void *myvar);

int main (void) {

    pthread_t thread1;
    int waitms;

    while(globalVariable <= 50){
        printf("Main function: %d \n", globalVariable);

        if (globalVariable==9) {
            pthread_create(&thread1, NULL, myfunc, NULL);
            pthread_join(thread1, NULL);
        }
        usleep(300000);

    globalVariable++;
    }
    return 0;
}

void *myfunc (void *myvar){

    int waitms;

    while(globalVariable<=50) {

        printf("Thread1: %d \n", globalVariable);

        usleep(300000);

        globalVariable++;
    }
    return 0;

}

The code must print a value of a global variable that is incremented in the main function. When this variable has the value 9, the main function calls a thread, that does the same as the original main function, but without calling another thread.

In the Output I get the first 9 prints of the main function and all the following ones are from the thread. Shouldn't they be mixed? What have I done wrong?

È stato utile?

Soluzione

No because you are joining the thread1, so the main thread blocks until thread1 dies. Once thread1 dies it resumes but thread1 has incremented the globalVariable to a point where the main thread exits the first while loop.

Removing the join you will see mixed results, better still would be to move the join outside of the while loop so if thread1 is still alive when the main thread exits the loop it waits... it's most likely going to dead by that time but you should make sure your child threads have finished up before exiting the main thread.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top