Operating System Lab – Thread Examples
1. Objectives
By the end of this lab, you should be able to:
1. Create and manage multiple threads in C using the pthread library.
2. Share data between threads safely.
3. Observe race conditions.
4. Measure performance differences between single-threaded and multi-threaded code.
2. Theory Overview
A thread is a lightweight unit of execution within a process. Threads share address space, open files, and
global variables with other threads of the same process.
Why threads?
- Enable parallelism on multi-core CPUs
- Improve responsiveness
- More efficient for certain workloads
Common POSIX Thread (pthreads) API:
- pthread_create
- pthread_join
- pthread_mutex_t
- pthread_mutex_lock / pthread_mutex_unlock
Compile using:
gcc -pthread file.c -o program
1
3. Part A – Simple Thread Creation
Task A1: Hello from Threads
Example Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* print_message(void* arg) {
char* text = (char*)arg;
printf("Thread says: %s\n", text);
return NULL;
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, print_message, "Hello from thread 1");
pthread_create(&t2, NULL, print_message, "Hello from thread 2");
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("Main thread finished.\n");
return 0;
Tasks:
1. Compile and run.
2. Observe output order.
3. Explain why thread order changes.
2
4. Part B – Array Sum (Single-threaded & Multi-threaded)
Task B1: Single-threaded Sum
Example Code:
long long single_thread_sum(int* arr, long long n) {
long long sum = 0;
for (long long i = 0; i < n; i++) {
sum += arr[i];
return sum;
Task B2: Multi-threaded Sum
Uses multiple pthreads to compute partial sums and combine them.
Compare:
- Runtime for 1, 2, 4, 8 threads
- Performance vs. single-threaded version
5. Part C – Race Condition Example
Task C1: Incrementing a shared counter without mutex
Example:
long long counter = 0;
void* increment(void* arg) {
for (int i = 0; i < 1000000; i++) {
counter++; // race condition
Run multiple times and observe incorrect results.
3
6. Part D – Fixing Race Condition with Mutex
Use pthread_mutex_t to protect counter++:
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&lock);
counter++;
pthread_mutex_unlock(&lock);