lock-contention
Table of Contents
Lock contention
Lock contention occurs when multiple threads frequently compete for the same lock, forcing some to wait rather than run. Contention doesn't scale linearly—it grows disproportionately as more threads compete because failed attempts generate cache-coherence traffic and each waiting thread adds synchronization overhead.
Fix contention by reducing the critical section, sharding locks across data slices, or using lock-free structures entirely.
Example
This example shows how contention degrades throughput as thread count increases.
// compile: gcc -std=c11 -pthread -O2 -o contention contention.c // run: ./contention // description: demonstrate lock contention degradation with more threads #include <stdio.h> #include <pthread.h> #include <stdatomic.h> #include <time.h> atomic_int counter = 0; atomic_flag lock = ATOMIC_FLAG_INIT; void* worker(void* arg) { int iterations = *(int*)arg; for (int i = 0; i < iterations; i++) { while (atomic_flag_test_and_set(&lock)) { } counter++; atomic_flag_clear(&lock); } return NULL; } int main() { int iterations = 1000000; for (int num_threads = 1; num_threads <= 8; num_threads *= 2) { counter = 0; pthread_t threads[num_threads]; clock_t start = clock(); for (int i = 0; i < num_threads; i++) { pthread_create(&threads[i], NULL, worker, &iterations); } for (int i = 0; i < num_threads; i++) { pthread_join(threads[i], NULL); } clock_t end = clock(); printf("Threads: %d, Time: %ld, Counter: %d\n", num_threads, end - start, atomic_load(&counter)); } return 0; }
lock-contention.md · Last modified: by 127.0.0.1
