Mutexes in C
A mutex serializes access, so two threads never update the counter at once.
#include <pthread.h>
typedef struct {
long count;
pthread_mutex_t lock;
} Counter;
void counter_init(Counter *c) {
c->count = 0;
pthread_mutex_init(&c->lock, NULL);
}
void counter_add(Counter *c, long n) {
pthread_mutex_lock(&c->lock);
c->count += n;
pthread_mutex_unlock(&c->lock);
}
long counter_read(Counter *c) {
pthread_mutex_lock(&c->lock);
long value = c->count;
pthread_mutex_unlock(&c->lock);
return value;
}
void counter_destroy(Counter *c) {
pthread_mutex_destroy(&c->lock);
}
How it works
- Lock, touch the shared state, unlock — keep the region small.
- Every return path must unlock, or the next thread waits forever.
- Without the lock the increment is a read, an add and a write.
Keywords and builtins used here
NULLcounter_addcounter_destroycounter_initcounter_readlongreturnstructtypedefvoid
The run, in numbers
- Lines
- 28
- Characters to type
- 492
- Tokens
- 136
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 78 seconds.
Step 1 of 4 in Locking, step 4 of 10 in Threads & concurrency.