A comprehensive exploration of thread synchronization concepts in C using POSIX threads (pthreads). This repository contains a series of progressively complex programs that demonstrate threading fundamentals, race conditions, and synchronization mechanisms.
This collection of C programs illustrates the evolution from single-threaded to multi-threaded programming, highlighting common pitfalls and their solutions. Each task builds upon the previous one, introducing new concepts and demonstrating both correct and incorrect approaches to concurrent programming.
Basic counting program that increments a global sum variable 500,000,000 times using a single thread.
Extends Task1 by adding a second function call that decrements the sum, demonstrating sequential execution.
Introduces pthread library usage by converting the counting function to run in a separate thread.
Creates two threads that run sequentially - one increments and one decrements the global sum.
Demonstrates a race condition by running two threads concurrently without proper synchronization.
Fixes the race condition from Task5 by implementing mutex locks around the critical section.
Reduces the loop count to 20,000,000 and introduces a subtle bug by reusing the same offset variable for both threads.
Further reduces the loop count to 2,000,000 to make the race condition more apparent and easier to observe.
Corrects the variable sharing issue from Tasks 7 and 8 by using separate offset variables for each thread.
Demonstrates a scenario with only 100 iterations where race conditions are less likely to occur due to the minimal execution time.
- Thread Creation and Management: Using
pthread_create()andpthread_join() - Race Conditions: How concurrent access to shared variables can lead to unpredictable results
- Mutex Synchronization: Using
pthread_mutex_lock()andpthread_mutex_unlock()to protect critical sections - Critical Sections: Identifying code segments that require exclusive access
- Thread Timing Issues: How thread execution order affects program outcomes
To compile any of the programs:
gcc -pthread TaskX.c -o TaskXTo run a program:
./TaskXTo measure execution time:
time ./TaskX- Tasks 1, 3: Sum = 500000000
- Tasks 2, 4, 6, 9, 10: Sum = 0 (correct synchronization)
- Task 5: Unpredictable result due to race condition
- Tasks 7, 8: May show incorrect results due to variable sharing issues
- GCC compiler with pthread support
- POSIX-compliant system (Linux, macOS, Unix)
- pthread library