Lab Assignment 3 CP
Lab Assignment 3 CP
Lab Objective
The goal of this experiment is to:
Design and implement a program that demonstrates the safety and liveness properties of mutual
exclusion.
Use mutex locks to enforce safety in concurrent programming.
Test different conditions to analyze liveness issues, such as deadlock and starvation.
Prerequisites
Before starting this experiment, students should be familiar with:
1. C Programming Basics
2. Multithreading Concepts
o Creating and managing threads using pthread_create()
o Joining threads using pthread_join()
3. Mutex Locks in C
o pthread_mutex_t for synchronization of shared resources.
o Preventing race conditions by ensuring only one thread accesses critical sections at a time.
4. Safety and Liveness in Mutual Exclusion
o Safety Property: No two threads access the critical section at the same time.
o Liveness Property: Every thread eventually makes progress without indefinite blocking (no
deadlocks or starvation).
Expected Outcome
Students will understand the concepts of safety and liveness in concurrent programming.
They will learn how to use locks to ensure mutual exclusion and prevent race conditions.
They will experiment with various testing scenarios to analyze safety and liveness violations.
Step-by-Step Implementation
1. Implementing a Basic Mutual Exclusion Program
1️⃣ Ensuring Safety (No Two Threads Access the Critical Section Simultaneously)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_THREADS 3
#define ITERATIONS 5
return NULL;
int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
pthread_mutex_init(&lock, NULL); // Initialize mutex lock
thread_ids[i] = i + 1;
pthread_join(threads[i], NULL);
return 0;
Expected Output
...
This ensures safety, as only one thread is in the critical section at any given time.
Deadlock Scenario
A deadlock occurs when two or more threads are waiting for resources that will never be released.
Scenario Analysis
Testing Scenarios
Safety Property Testing
Run the first program and check no two threads enter the critical section simultaneously.
If two threads access the shared resource at the same time, it means mutual exclusion is violated.
Key Takeaways
1. Safety Property
o Ensures mutual exclusion: Only one thread enters the critical section at a time.
o Avoids race conditions, ensuring data consistency.
2. Liveness Property
o Ensures progress: Every thread gets a chance to execute.
o Avoids deadlock (threads stuck waiting for resources).
o Avoids starvation (one thread waiting indefinitely while others execute).
3. Deadlocks and Starvation
o Deadlock happens if a thread locks but never unlocks.
o Starvation happens if a thread never gets a chance to execute due to unfair scheduling.
o Both can be avoided using proper lock management.
Further Enhancements
Would you like me to extend this with: