Read-write locks in C
Many readers together, or one writer alone.
#define _POSIX_C_SOURCE 200809L
#include <pthread.h>
typedef struct {
int values[16];
size_t count;
pthread_rwlock_t lock;
} Table;
void table_init(Table *t) {
t->count = 0;
pthread_rwlock_init(&t->lock, NULL);
}
int table_append(Table *t, int value) {
pthread_rwlock_wrlock(&t->lock);
int ok = t->count < 16;
if (ok) {
t->values[t->count++] = value;
}
pthread_rwlock_unlock(&t->lock);
return ok;
}
size_t table_size(Table *t) {
pthread_rwlock_rdlock(&t->lock);
size_t n = t->count;
pthread_rwlock_unlock(&t->lock);
return n;
}
How it works
rdlockmay be held by several threads at once.wrlockwaits for every reader to leave.- Both are released by the same
unlockcall.
Keywords and builtins used here
NULLifintreturnsize_tstructtable_appendtable_inittable_sizetypedefvoid
The run, in numbers
- Lines
- 31
- Characters to type
- 532
- Tokens
- 152
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 87 seconds.
Step 3 of 4 in Locking, step 6 of 10 in Threads & concurrency.