Implement a reader-writer lock.
#include <pthread.h>
typedef struct {
pthread_mutex_t m;
pthread_cond_t readers_ok, writer_ok;
int readers; /* active readers */
int writer; /* 1 if a writer holds the lock */
int waiting_writers; /* writer preference: block new readers while writers wait */
} rwlock_t;
void rw_init(rwlock_t *l)
{
pthread_mutex_init(&l->m, NULL);
pthread_cond_init(&l->readers_ok, NULL);
pthread_cond_init(&l->writer_ok, NULL);
l->readers = l->writer = l->waiting_writers = 0;
}
void rw_read_lock(rwlock_t *l)
{
pthread_mutex_lock(&l->m);
while (l->writer || l->waiting_writers > 0)
pthread_cond_wait(&l->readers_ok, &l->m);
l->readers++;
pthread_mutex_unlock(&l->m);
}
void rw_read_unlock(rwlock_t *l)
{
pthread_mutex_lock(&l->m);
if (--l->readers == 0) pthread_cond_signal(&l->writer_ok);
pthread_mutex_unlock(&l->m);
}
void rw_write_lock(rwlock_t *l)
{
pthread_mutex_lock(&l->m);
l->waiting_writers++;
while (l->writer || l->readers > 0)
pthread_cond_wait(&l->writer_ok, &l->m);
l->waiting_writers--;
l->writer = 1;
pthread_mutex_unlock(&l->m);
}
void rw_write_unlock(rwlock_t *l)
{
pthread_mutex_lock(&l->m);
l->writer = 0;
if (l->waiting_writers) pthread_cond_signal(&l->writer_ok);
else pthread_cond_broadcast(&l->readers_ok); /* let all waiting readers in */
pthread_mutex_unlock(&l->m);
}
Points: many readers may hold the lock together, a writer needs exclusive access. Choose a policy: reader preference can starve writers; writer preference (as here) can starve readers under constant writes; fair (FIFO) versions avoid both. Use rwlocks only for read-mostly data with non-trivial read sections; for tiny sections a plain mutex is often faster. Kernel alternatives for read-mostly data: seqlocks and RCU. POSIX provides pthread_rwlock_t.