Site Tools


lock

Table of Contents

Lock

Lock is a synchronization mechanism that grants exclusive or limited access to a shared resource among threads. Every lock is built from an atomic read-modify-write instruction for claiming ownership and a waiting policy (spin, sleep, or hybrid) for what a thread does if it cannot claim the resource immediately.

The choice between spinning and blocking depends on expected wait time: spinning is cheap for short waits, blocking avoids wasting CPU for long waits.

Example

This example implements a simple spinlock using atomic operations.

// compile: gcc -std=c11 -pthread -O2 -o lock lock.c
// run: ./lock
// description: simple spinlock implementation using atomics
 
#include <stdio.h>
#include <pthread.h>
#include <stdatomic.h>
 
typedef atomic_flag spinlock_t;
 
void lock_acquire(spinlock_t* lock) {
    while (atomic_flag_test_and_set(lock)) {
        // spin
    }
}
 
void lock_release(spinlock_t* lock) {
    atomic_flag_clear(lock);
}
 
static int counter = 0;
static spinlock_t lock = ATOMIC_FLAG_INIT;
 
void* worker(void* arg) {
    for (int i = 0; i < 1000000; i++) {
        lock_acquire(&lock);
        counter++;
        lock_release(&lock);
    }
    return NULL;
}
 
int main() {
    pthread_t t1, t2;
    pthread_create(&t1, NULL, worker, NULL);
    pthread_create(&t2, NULL, worker, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    printf("Counter: %d (expected 2000000)\n", counter);
    return 0;
}
lock.md · Last modified: by 127.0.0.1