Open In App

Thread Management Functions in C

Last Updated : 21 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C language, POSIX <pthread.h> standard API (Application program Interface) for all thread related functions. It allows us to create multiple threads for concurrent process flows.

To execute the C programs that uses these functions, we may have to use the -pthread or -lpthread in the command line while compiling the file.

C
gcc -pthread file.c
gcc -lpthread file.c

The below table lists some of the most commonly used thread management functions in C:

FunctionDescription
pthread_create()Creates a new thread and starts execution. Takes a function pointer that will be executed in the new thread.
pthread_exit()Terminates the calling thread. This does not affect other threads.
pthread_join()Waits for the specified thread to terminate. It blocks the calling thread until the target thread finishes.
pthread_detach()Detaches a thread, meaning it will automatically release resources when it terminates without needing pthread_join().
pthread_cancel()Requests cancellation of a thread. The thread must check periodically for cancellation to exit safely.
pthread_self()Returns the thread ID of the calling thread.
pthread_equal()Compares two thread IDs and returns non-zero if they are the same, zero otherwise.
pthread_mutex_init()Initializes a mutex, which is used to prevent race conditions in concurrent programming.
pthread_mutex_destroy()Destroys a mutex when it's no longer needed.
pthread_mutex_lock()Locks a mutex. If the mutex is already locked by another thread, the calling thread will be blocked.
pthread_mutex_unlock()Unlocks a mutex that was previously locked by the calling thread.
pthread_cond_init()Initializes a condition variable, used for synchronization between threads.
pthread_cond_destroy()Destroys a condition variable.
pthread_cond_wait()Blocks the calling thread until the condition variable is signaled.
pthread_cond_signal()Wakes up one thread that is waiting on a condition variable.
pthread_cond_broadcast()Wakes up all threads waiting on a condition variable.

Let's discuss some of them with examples.

pthread_create()

To create a new thread, we use the pthread_create() function provided by the thread library in C. It initializes and starts the thread to run the given function.

Syntax:

C
pthread_create(thread, attr, routine, arg);

where,

  • thread : Pointer to a pthread_t variable where the system can store the ID of the new thread.
  • attr : Pointer to a thread attributes object that defines thread properties. Use NULL for default attributes.
  • routine: Pointer to the function that the thread will execute. It must return void* and accept a void* argument.
  • arg: A single argument passed to the thread function. Use NULL if no argument is needed. We can pass a struct or pointer to pass multiple values.

Example:

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

void* foo(void* arg) {
    printf("Created a new thread");
    return NULL;
}
int main() {
    pthread_t thread1;
    
    // Creating a new thread
    pthread_create(&thread1, NULL, foo, NULL);
    
    pthread_join(thread1, NULL);
    return 0;
}


Output

Created a new thread

pthread_join()

pthread_join() function allows one thread to wait for the termination of another thread. It is used to synchronize the execution of threads.

Syntax

C
pthread_join(thread, retval);

Parameters

  • thread: The ID of the thread you want to wait for. This is the thread that will be joined.
  • retval: A pointer to a location where the exit status of the thread will be stored. This is optional and can be set to NULL if you do not need the return value of the thread.

Return Value

  • 0: Upon successful joining of the thread
  • EDEADLK: If the thread calling pthread_join is trying to join with itself.
  • ESRCH: If the thread ID is not valid or the calling thread does not exist.

Example

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

void* foo(void* arg) {
    printf("%s\n", (char*)arg);
    return NULL;
}

int main() {
    pthread_t thread1, thread2;

    // Create thread 1
    pthread_create(&thread1, NULL, foo,
        (void*)"Thread1 is running.");

    // Create thread 2
    pthread_create(&thread2, NULL, foo,
        (void*)"Thread2 is running.");

    // Wait for thread 1 to finish
    pthread_join(thread1, NULL);

    // Wait for thread 2 to finish
    pthread_join(thread2, NULL);

    printf("Both threads end.");

    return 0;
}


Output

Thread1 is running.
Thread2 is running.
Both threads end.

Note: If we do not use the pthread.join() then the main thread may end before the execution of the created thread and it may lead to unexpected behaviour of the program.

pthread_exit()

pthread_exit() function allows a thread to terminate its execution explicitly. pthread_exit is called when a thread needs to terminate its execution and optionally return a value to threads that are waiting for it.

Syntax

C
pthread_exit(retval);

Parameters

  • retval: A pointer to the value that will be returned to any thread that calls pthread_join on this thread. This can be NULL if no value is to be returned.

Example

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

void* foo(void* arg) {
    printf("Thread is running.\n");
    
    // Explicity terminate the thread
    pthread_exit(NULL);
    
    printf("This will not be executed\n");
    
    return NULL;
}

int main() {
    pthread_t thread;
    pthread_create(&thread, NULL, foo, NULL);
    pthread_join(thread, NULL);
    return 0;
}


Output

Thread is running.

pthread_cancel()

pthread_cancelfunction is used to request the cancellation of a thread. It sends a cancellation request to the target thread, but the actual termination depends on whether the thread is in a cancelable state and if it handles cancellation.

Syntax:

C
pthread_cancel(thread);

Parameters:

  • thread: The thread ID of the thread you want to cancel. This is the thread that will receive the cancellation request.

Example:

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

void* myThreadFunc(void* arg) {
    while(1) {
        printf("Thread is running...\n");
        sleep(1);
    }
    return NULL;
}

int main() {
    pthread_t thread;
    pthread_create(&thread, NULL, myThreadFunc, NULL);
    sleep(5);
    //Requesting to cancel the thread after 5 seconds. 
    pthread_cancel(thread);
    // Wait for the thread to terminate
    pthread_join(thread, NULL);  

    printf("Main thread finished.\n");
    return 0;
}


Output:

Thread is running...
Thread is running...
Thread is running...
Thread is running...
Thread is running...
Thread is running...
Main thread finished.

pthread_detach()

pthread_detach() function is used to detach a thread from the calling thread. Once a thread is detached, it cannot be joined, and its resources will be automatically released when the thread terminates. Detaching a thread is useful when you want the system to handle resource deallocation without waiting for the thread to complete

Syntax:

C
pthread_detach(thread);

Parameters:

  • thread: The thread ID of the thread you want to detach.

Return Value:

  • 0: On success.
  • ESRCH: If no thread with the specified thread ID exists.
  • EINVAL: If the thread is already detached or if the thread is in a non-existent state.

Example:

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

void* myThreadFunc(void* arg) {
    printf("Thread1 is running...\n");
    sleep(2);
    printf("Thread1 finished.\n");
    return NULL;
}

int main() {
    pthread_t thread1;
    pthread_create(&thread1, NULL, myThreadFunc, NULL);

    // Detach the thread so that its resources will be automatically cleaned up
    pthread_detach(thread1);

    // Main thread continues without waiting for the detached thread
    printf("Main thread continues...\n");

    // Sleep to allow detached thread to finish
    sleep(3);
    return 0;
}


Output

Main thread continues...
Thread1 is running...
Thread1 finished.

pthread_self()

pthread_self function returns the thread ID of the calling thread. This is useful when you need to identify or store the ID of the current thread in multi-threaded programs.

Syntax:

C
pthread_self();

Return Value

  • pthread_t: It returns the thread ID of the calling thread.

Example:

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

void* myThreadFunc(void* arg) {
    pthread_t currentThread = pthread_self();  // Get the current thread ID
    printf("Current thread ID: %lu\n", (unsigned long)currentThread);
    return NULL;
}

int main() {
    pthread_t thread1;
    pthread_create(&thread1, NULL, myThreadFunc, NULL);
    pthread_join(thread1, NULL);  // Wait for the thread to finish
    return 0;
}


Output

Current thread ID: 134681321096896

pthread_equal()

pthread_equal() function is used to compare two thread IDs to check if they refer to the same thread. It returns a non-zero value if both thread IDs refer to the same thread otherwise returns zero.

C
pthread_equal(t1, t2);

Parameters:

  • t1: The first thread ID to compare.
  • t2: The second thread ID to compare.

Return value:

  • 0: If the two thread IDs are equal, i.e., they refer to the same thread.
  • Non-zero: If the two thread IDs are not equal, i.e., they refer to different threads.

Example:

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

void* myThreadFunc(void* arg) {
    pthread_t threadId = pthread_self();  // Get the current thread ID
    printf("ID of Current thread: %lu\n", (unsigned long)threadId);
    return NULL;
}

int main() {
    pthread_t thread1, thread2;
    
    // Creating the threads
    pthread_create(&thread1, NULL, myThreadFunc, NULL);
    pthread_create(&thread2, NULL, myThreadFunc, NULL);

    // Joining the threads
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    if (pthread_equal(thread1, thread2)) {
        printf("The threads are the same.\n");
    } else {
        printf("The threads are different.\n");
    }

    return 0;
}


Output

ID of Current thread: 135272657200832
ID of Current thread: 135272648808128
The threads are different.

Next Article

Similar Reads