thesyrupkidd
thesyrupkidd

Reputation: 11

Can someone explain this multithreading code in C?

I am having a really hard time understanding multithread code. I have this example code where I am supposed to be able to explain what output is written on the two commented lines. Can someone explain how I can determine the output here?

#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/wait.h>

int value = 0;

void *runner(void *param);

int main(int argc, char *argv[]){
    pid_t pid;
    pthread_t tid;
    pthread_attr_t attr;
    pid = fork();
    
    if (pid == 0) { /* child process */
        pthread_attr_init(&attr);
        pthread_create(&tid,&attr,runner,NULL);
        pthread_join(tid,NULL);
        printf("CHILD: value = %d",value); /* LINE C */
        }
    else if (pid > 0){ /* parent process */
        wait(NULL);
        printf("PARENT: value = %d",value); /* LINE P */
    }}

void *runner(void *param){
    value = 5;
    pthread_exit(0);
}

Upvotes: 0

Views: 79

Answers (1)

selbie
selbie

Reputation: 104524

  • The process starts. It forks into a child process as well.

    • The parent process waits for the child process to finish.

      • The child process starts a thread and waits for it to complete via pthread_join

        • The thread sets the global memory variable, value, to 5.

        • The thread exits

      • The child process, upon returning from pthread_join, prints "CHILD: value = 5".

      • The child process exits.

    • The parent process, upon returning from wait, prints: "PARENT: value = 0". value is 0 since processes don not the same memory space with other processes. (Threads in the same process share the same memory space).

  • The parent process exits

Minor nit: The fact that the child process doesn't print an end of line char, \n, might create some weird overlapping results on the console. Consider adding a \n to each printf statement.

Upvotes: 4

Related Questions