Exit main thread and keep other threads running in C

Summary

In C programming, terminating only the main thread while allowing other threads to continue execution requires a specific approach. Directly using `return` in the `main` function will terminate the entire process, halting all active threads. To prevent this, developers can employ `thrd_exit` within the `main` function, which gracefully exits the main thread without affecting other concurrently running threads. A provided code example illustrates this by spawning a detached thread that performs a task, while the main thread immediately calls `thrd_exit`, demonstrating that the spawned thread continues its execution independently. This technique is crucial for scenarios where background operations must persist after the primary execution flow concludes.

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

  COMMENTS

0

No comment for this article.