Course contentsShow
← C
Lesson 1119 of 1,21915. Systems ProgrammingFree lesson

Waiting for threads with pthread_join

Waiting for threads with pthread_join

What you'll learn: How to pause your main program until a background thread finishes its work to ensure data integrity and prevent premature exit.

The "Parent" Problem

When you call pthread_create, your program splits. The main thread keeps running while the new thread handles its task separately. However, there is a catch: if your main() function reaches its end and returns, the entire process terminates—even if your background threads are still working.

Think of it like a parent (the main thread) sending a child (the new thread) to the grocery store. If the parent finishes their chores and decides to lock the front door and go to sleep before the child gets home, the child is effectively locked out and their task is cut short. To prevent this, the parent must sit by the door and wait for the child to return. In C, we call this "joining."

Using pthread_join

The pthread_join() function acts as a synchronization point. It tells the calling thread to stop and wait until a specific thread has finished executing.

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

void* cook_meal(void* arg) {
    printf("Thread: Cooking dinner...\n");
    // Simulate work
    return NULL;
}

int main() {
    pthread_t thread_id;

    // Start the thread
    pthread_create(&thread_id, NULL, cook_meal, NULL);

    printf("Main: Waiting for the thread to finish...\n");

    // Wait (join) for the thread to finish
    pthread_join(thread_id, NULL);

    printf("Main: The thread is done. Now I can safely exit.\n");
    return 0;
}

Why Joining Matters

Joining serves two critical purposes:

  1. Execution Order: It ensures the main program doesn't finish before the background work is done.
  2. Resource Cleanup: When a thread finishes, it stays in a "zombie" state, holding onto some system resources. pthread_join acts like a cleanup crew, officially acknowledging the thread's completion and releasing its memory back to the system.

If you don't join your threads, you risk your program closing early, leaving tasks half-finished or leaking resources. By joining, you ensure that even though the work happened in parallel, the final result is gathered safely before the program concludes.

Key takeaway

pthread_join pauses the current thread until the specified thread terminates, ensuring the program doesn't exit prematurely and cleaning up thread resources.