Exit main thread and keep other threads running in C

  sonic0002        2020-08-14 21:20:04       1,621        0    

In C programming, if using return in main function, the whole process will terminate. To only let main thread gone, and keep other threads live, you can use thrd_exit in main function. Check following code:

#include 
#include 
#include 

int
print_thread(void *s)
{
    thrd_detach(thrd_current());
    for (size_t i = 0; i < 5; i++)
    {
        sleep(1);
        printf("i=%zu\n", i);
    }
    thrd_exit(0);
}

int
main(void)
{
    thrd_t tid;
    if (thrd_success != thrd_create(&tid, print_thread, NULL)) {
        fprintf(stderr, "Create thread error\n");
        return 1;
    }
    thrd_exit(0);
}

Run it:

$ ./main
i=0
i=1
i=2
i=3
i=4

You can see even main thread exited, the other thread still worked.

P.S., the code can be downloaded here.

 

Note: this post is authorized to republish here by original author Nan Xiao and the original post can be found at here.

C LANGUAGE  MULITHREAD  MAIN THREAD 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

How to write proper resume