The pthread_exit function
What you'll learn: How to gracefully terminate a single thread without shutting down your entire program.
Quitting the team, not the company
Imagine a busy restaurant kitchen where several chefs (threads) are working on different dishes. If the pastry chef finishes the dessert early, they should be able to clock out and go home without the head chef closing the entire restaurant.
In C, if you use the standard exit() function, it’s like pulling the fire alarm; it kills the process and every thread inside it immediately. The pthread_exit() function is the professional alternative. It allows an individual thread to stop executing and return a result while letting the rest of the program continue its work.
Why not just use "return"?
In your main() thread, using return is effectively the same as calling exit(). However, in a worker thread, calling pthread_exit() ensures the thread cleans up its resources and passes a specific exit status back to the "joiner" (the thread waiting for it).
Crucially, if you call pthread_exit() in your main function, the main thread will stop, but the process will stay alive until every other background thread has finished. This prevents the "parent" from accidentally killing its "children" before they are done.
Using pthread_exit in code
Here is how a thread says goodbye and passes back a status message:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* finish_early(void* arg) {
printf("Thread is working...\n");
// Create a status message on the heap
char *message = malloc(20 * sizeof(char));
sprintf(message, "Task Complete!");
// Terminate only this thread and return the message
pthread_exit((void*)message);
// This line will never be reached
printf("This will not print.\n");
return NULL;
}
int main() {
pthread_t my_thread;
void *status;
pthread_create(&my_thread, NULL, finish_early, NULL);
// Wait for the thread and grab its exit status
pthread_join(my_thread, &status);
printf("Thread exited with: %s\n", (char*)status);
free(status); // Clean up the returned memory
return 0;
}
When to use it
Use pthread_exit() when you have complex logic where a thread needs to stop deep inside a nested function, or when you want the main thread to finish its own work but allow background threads to keep processing in the background.
Key takeaway
pthread_exit() shuts down the current thread and returns a value, allowing the rest of the process to keep running safely.