Thread Management Functions in C
Last Updated :
21 May, 2025
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:
Function | Description |
---|
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
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
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
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
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
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.
Similar Reads
tan() Function in C
tan() function in C programming is provided by the math.h header file and it is used to calculate the tangent of an angle x where x is represented in radians. This function returns the tangent of a given angle value in radians and it only works for right-angled triangles. Syntax of tan() double tan(
2 min read
time() function in C
The time() function is defined in time.h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.Syntax: time_t time( time_t *seco
1 min read
remquo() Function in C
The remquo() function in C is part of the standard math library <math.h> and is used to compute the remainder and part of the quotient of the division of two floating-point numbers. This function is particularly useful when we need both the remainder and some information about the quotient sim
3 min read
sqrt() Function in C
sqrt() function in C is a predefined function in the math.h library used to calculate the square root of a given number. To use this function, we must include the <math.h> header file in our program. It returns the square root of the number as a double and works with double data types, for oth
3 min read
C Library Functions
The Standard Function Library in C is a huge library of sub-libraries, each of which contains the code for several functions. In order to make use of these libraries, link each library in the broader library through the use of header files. The actual definitions of these functions are stored in sep
9 min read
C Functions Practice Problems
Functions are the basic building block of C programs. They enhance the modularity and code reusability by separating the logic of a particular task from the main code and using it whenever required. Functions are extensively used in almost all programs, so it is best for programmers to be familiar i
2 min read
time.h localtime() function in C with Examples
The localtime() function is defined in the time.h header file. The localtime( ) function return the local time of the user i.e time present at the task bar in computer. Syntax: tm* localtime(const time_t* t_ptr); Parameter: This function accepts a parameter t_ptr which represents the pointer to time
1 min read
ToDo App in C Language
ToDo List App is a kind of app that generally used to maintain our day-to-day tasks or list everything that we have to do, with the most important tasks at the top of the list, and the least important tasks at the bottom. It is helpful in planning our daily schedules. We can add more tasks at any ti
10 min read
C log() Function
log() function in C programming is a mathematical function provided by the math.h header file and is used to calculate the natural logarithm (base(e)) of a given number passed as parameter. This function returns natural logarithm of x as double and works with double data types for other data types l
3 min read
fdim() Function in C
The fdim() function in C is part of the standard math library <math.h> and is used to compute the positive difference between two floating-point numbers. This function is particularly useful when we need to determine the non-negative difference between two given values. It returns the differen
3 min read