Search code examples
cmultithreadingpthreadspthread-join

Pthread in C basic print


I'm writing a C program using Pthreads that creates a child thread. After creating the child thread, the parent thread should ouput two messages: "parent:begin" then it should print "parent:done". Same for child thread "child:begin" and "child:done". I have to make sure that the main thread prints his second message before the spawned (child) thread does. I have to following implementation but it only prints in the wrong order. I assume I should use flags. Any help would be appreciated.

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


volatile int done = 0;

void *child(void *arg) {
 printf("child\n");
done = 1;
 printf("child:done");
return NULL;
 }

int main(int argc, char *argv[]) {
 printf("parent: begin\n");
 pthread_t c;
 pthread_create(&c, NULL, child, NULL); // create child
 while (done == 0); // spin
 printf("parent: end\n");
 return 0;
 }

Solution

  • If you want the parent to print done first, then you should have the child thread spin until the parent is done. (Right now the parent spins waiting for the child.) You should also use pthread_join to make sure the child is done before the main thread returns:

    #include <unistd.h>
    #include <stdio.h>
    #include <pthread.h>
    
    
    volatile int done = 0;
    
    void *child(void *arg) {
        printf("child: begin\n");
        while (done == 0); // spin
        printf("child: done\n");
        return NULL;
    }
    
    int main(int argc, char *argv[]) {
        printf("parent: begin\n");
        pthread_t c;
        pthread_create(&c, NULL, child, NULL); // create child
        printf("parent: done\n");
        done = 1;
        pthread_join(c, NULL);
        return 0;
    }
    

    On my machine I get this output:

    parent: begin
    parent: done
    child: begin
    child: done