Sync Techniques
Semaphores
Binary Semaphore
A synchronization primitive with two states: 0 and 1.
#include <semaphore.h>
sem_t binary_semaphore;
sem_init(&binary_semaphore, 0, 1);
Counting Semaphore
Allows multiple concurrent accesses up to a specified limit.
graph TD
A[Semaphore Value] --> |Decrements| B[Resource Acquired]
B --> |Increments| A
Mutex Locks
Characteristics
- Provides mutual exclusion
- Ensures only one thread can access a critical section
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex);
// Critical section
pthread_mutex_unlock(&mutex);
Condition Variables
Synchronization Mechanism
Allows threads to wait for specific conditions.
Operation |
Description |
wait() |
Suspends thread until signaled |
signal() |
Wakes up waiting threads |
broadcast() |
Wakes all waiting threads |
Atomic Operations
Fundamental Synchronization Technique
Guarantees indivisible execution of operations.
#include <stdatomic.h>
atomic_int counter;
atomic_fetch_add(&counter, 1);
Barriers
Synchronization Point
Ensures all threads complete a phase before proceeding.
pthread_barrier_t barrier;
pthread_barrier_init(&barrier, NULL, thread_count);
pthread_barrier_wait(&barrier);
Read-Write Locks
Concurrent Read, Exclusive Write
Allows multiple simultaneous reads, single write.
pthread_rwlock_t rwlock;
pthread_rwlock_rdlock(&rwlock); // Read lock
pthread_rwlock_wrlock(&rwlock); // Write lock
Advanced Synchronization Techniques
Lock-Free Algorithms
- Minimize lock contention
- Improve concurrent performance
At LabEx, we emphasize understanding these synchronization techniques for efficient system programming.