THEORY:
Multithreading allows a program to perform multiple tasks concurrently by creating separate
threads of execution within a single process. In C, this is commonly achieved using the POSIX
threads (pthreads) library, which provides functions for thread creation, management, and
synchronization.
Key pthread functions:
pthread_create(): Creates a new thread to run a specified function.
pthread_join(): Waits for a specific thread to finish execution.
pthread_exit(): Terminates the calling thread.
Synchronization primitives like mutexes (pthread_mutex_t) and condition variables
(pthread_cond_t) are used to coordinate thread actions and protect shared resources
SOURCE CODE
#include <stdio.h>
#include <pthread.h>
// Thread function to be executed
void* task(void* arg) {
long id = (long)arg;
printf("Thread %ld is running\n", id);
// Simulate some work
printf("Thread %ld finished its task\n", id);
return NULL;
}
int main() {
int numberOfThreads = 5;
pthread_t threads[numberOfThreads];
// Create multiple threads
for (long i = 0; i < numberOfThreads; i++) {
if (pthread_create(&threads[i], NULL, task, (void*)i) != 0) {
perror("Failed to create thread");
return 1;
}
}
// Join the threads
for (int i = 0; i < numberOfThreads; i++) {
if (pthread_join(threads[i], NULL) != 0) {
perror("Failed to join thread");
return 1;
}
}
printf("All threads have finished.\n");
return 0;
}
OUTPUT:
Thread 0 is running
Thread 0 finished its task
Thread 1 is running
Thread 1 finished its task
Thread 2 is running
Thread 2 finished its task
Thread 3 is running
Thread 3 finished its task
Thread 4 is running
Thread 4 finished its task
All threads have finished.
Name: Kajal Kumari Chaudhary
Roll No. 080BCT037