Notes: How Pthreads (POSIX Threads) Work
1. Introduction to Threads
A thread is a small unit of a process that can run independently.
Multithreading allows multiple threads to run in parallel within the
same program.
Threads share the same memory space but have their own execution
path.
Example: Think of a program as a company and threads as workers inside
the company doing different tasks simultaneously.
2. Why Use Threads?
To make programs faster by doing multiple tasks at once.
To efficiently use CPU resources.
To handle multiple operations simultaneously (e.g., in web servers).
3. How Pthreads Work
Step 1 — Include pthread Library
#include <pthread.h>
This library contains all functions needed for thread creation and
management.
Step 2 — Create a Thread Function
void *thread_function(void *arg) {
int id = *(int *)arg;
printf("Thread %d is running\n", id);
pthread_exit(NULL);
}
void *arg is used to pass any data to the thread.
pthread_exit(NULL) ends the thread after execution.
Step 3 — Create Threads
pthread_t thread1, thread2;
int t1 = 1, t2 = 2;
pthread_create(&thread1, NULL, thread_function, (void *)&t1);
pthread_create(&thread2, NULL, thread_function, (void *)&t2);
pthread_create() starts a new thread.
Arguments: thread variable, attributes (NULL for default), function to
run, data to pass.
Step 4 — Wait for Threads to Finish
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
Ensures the main program waits until threads finish execution.
4. Full Example Code
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *thread_function(void *arg) {
int id = *(int *)arg;
printf("Thread %d is running\n", id);
pthread_exit(NULL);
}
int main() {
pthread_t thread1, thread2;
int t1 = 1, t2 = 2;
pthread_create(&thread1, NULL, thread_function, (void *)&t1);
pthread_create(&thread2, NULL, thread_function, (void *)&t2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("All threads have finished execution\n");
return 0;
}
Output:
Thread 1 is running
Thread 2 is running
All threads have finished execution
5. How Threads Work Internally
1. The main program starts.
2. Threads are created using pthread_create().
3. Threads run in parallel, sharing memory.
4. Each thread executes its function.
5. Threads finish execution.
6. Main program ends after all threads finish.
6. Real-Life Analogy
Program = Restaurant
Threads = Chefs
Chefs work on different dishes simultaneously.
They share the same kitchen (memory).
When all dishes are ready, the restaurant closes.
Key Points: - Threads help in multitasking. - Pthreads are used in Unix/Linux
systems. - Thread management includes creation, execution, and joining. -
Threads improve performance but require careful memory handling.