Course contentsShow
← C
Lesson 1138 of 1,21915. Systems ProgrammingFree lesson

Read-write locks basics

Read-write locks basics

What you'll learn: How to improve performance in multi-threaded programs by allowing multiple readers to access data simultaneously while keeping writers exclusive.

The problem with standard Mutexes

Imagine a public library. If a standard mutex governed the library, only one person could enter the building at a time. Even if 50 people just wanted to read books, they would have to wait in line for the person ahead of them to finish reading. This is inefficient because readers don't change the books; they don't interfere with each other.

A standard pthread_mutex_t is "exclusive"—it doesn't care if you are reading or writing. It simply locks everyone else out.

Enter the Read-Write Lock

A Read-Write Lock (pthread_rwlock_t) distinguishes between reading and writing. It follows two simple rules:

  1. Multiple Readers: Many threads can hold a "read lock" at the same time.
  2. One Writer: Only one thread can hold a "write lock," and it cannot grant access to anyone else (readers or writers) until it is finished.

This is perfect for data structures that are searched often but updated rarely, like a DNS cache or a user permissions list.

Using pthread_rwlock_t

The implementation in C using the POSIX library looks very similar to mutexes, but with different function calls for the type of access you need.

#include <pthread.h>

pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
int shared_data = 42;

void* reader(void* arg) {
    pthread_rwlock_rdlock(&lock); // Request read access
    // Multiple threads can be here at once
    printf("Data: %d\n", shared_data);
    pthread_rwlock_unlock(&lock);
    return NULL;
}

void* writer(void* arg) {
    pthread_rwlock_wrlock(&lock); // Request exclusive write access
    // Only ONE thread can be here; readers are blocked
    shared_data++;
    pthread_rwlock_unlock(&lock);
    return NULL;
}

When to use them

While read-write locks sound strictly better, they have more overhead than a simple mutex. You should use them when you have a high "read-to-write ratio." If your threads are writing just as often as they are reading, the extra complexity of the rwlock might actually slow your program down. However, when you have dozens of threads reading a configuration file, an rwlock prevents a massive bottleneck.

Key takeaway

Read-write locks allow parallel read access while maintaining exclusive write access, significantly boosting performance for read-heavy shared data.