Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Multithreaded using the Pthreads API
Pthreads refers to the POSIX standard (IEEE 1003.1c) that defines an API for thread creation and synchronization. This is a specification for thread behavior, not a specific implementation, allowing operating system designers to implement it according to their requirements.
The Pthreads API provides a standardized way to create multithreaded programs in C, enabling concurrent execution of multiple threads within a single process. Each thread shares the same memory space but can execute different parts of the program simultaneously.
How Pthreads Work
In a Pthreads program, separate threads begin execution in specified functions. The main thread starts in the main() function and can create additional threads that execute in other functions. All threads share global data, making synchronization important for data consistency.
Key Pthreads Functions
pthread_create()− Creates a new threadpthread_join()− Waits for a thread to terminatepthread_exit()− Terminates the calling threadpthread_attr_init()− Initializes thread attributes
Example − Multithreaded Summation Program
The following program demonstrates basic Pthreads usage by calculating the sum of integers from 1 to N in a separate thread:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int sum; /* Global variable shared by threads */
void *runner(void *param); /* Thread function */
int main(int argc, char *argv[]) {
pthread_t tid; /* Thread identifier */
pthread_attr_t attr; /* Thread attributes */
if (argc != 2) {
fprintf(stderr, "usage: %s <integer><br>", argv[0]);
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr, "%d must be >= 0<br>", atoi(argv[1]));
return -1;
}
/* Initialize thread attributes with defaults */
pthread_attr_init(&attr);
/* Create the summation thread */
pthread_create(&tid, &attr, runner, argv[1]);
/* Wait for the thread to complete */
pthread_join(tid, NULL);
printf("sum = %d<br>", sum);
return 0;
}
/* Thread function that calculates the sum */
void *runner(void *param) {
int i, upper = atoi(param);
sum = 0;
for (i = 1; i <= upper; i++)
sum += i;
pthread_exit(0);
}
Step-by-Step Execution
Initialization − The main thread starts and validates command-line arguments
Thread Creation −
pthread_create()creates a new thread that begins execution inrunner()Concurrent Execution − Both main and summation threads run simultaneously
Summation − The child thread calculates the sum and stores it in the global variable
Synchronization −
pthread_join()makes the main thread wait for the summation threadOutput − Main thread displays the result after the summation thread terminates
Thread Attributes
The pthread_attr_t structure contains thread attributes such as:
Stack size − Memory allocated for the thread's stack
Scheduling policy − How the thread is scheduled by the OS
Priority − Thread's execution priority
Detach state − Whether the thread is joinable or detached
Fork-Join Model
This program follows the fork-join strategy where the parent thread creates a child thread and waits for its completion before proceeding. This ensures proper synchronization and allows the main thread to access the result computed by the child thread.
Compilation and Execution
To compile and run a Pthreads program:
gcc -pthread sum.c -o sum ./sum 10
sum = 55
Conclusion
Pthreads provides a standardized API for creating multithreaded programs in C. The fork-join model allows parent threads to create child threads for parallel computation and synchronize using pthread_join(). Proper synchronization is crucial when threads share global data to ensure program correctness.
