
C program to implement queue data structure
September 08, 2025
1 min
This problem is a tricky question often asked during tech interviews. Here we need to create custom mutex_lock() and mutex_unlock() functions to mimick the actual behavior of mutex APIs. This program implements a mutex using atomic operations and busy waiting (spinning).
#include <stdio.h>#include <stdatomic.h>#include <pthread.h>typedef struct {atomic_flag flag;} Mutex;void Mutex_Init(Mutex* m) {atomic_flag_clear(&m->flag); // initially unlocked}void Mutex_Lock(Mutex* m) {while (atomic_flag_test_and_set(&m->flag)) {// Busy wait (spinning)}}void Mutex_Unlock(Mutex* m) {atomic_flag_clear(&m->flag);}Mutex mylock;void* worker(void* arg) {Mutex_Lock(&mylock);printf("Thread %ld entered critical section\n", (long)arg);for (volatile int i = 0; i < 100000000; i++); // simulate workprintf("Thread %ld leaving critical section\n", (long)arg);Mutex_Unlock(&mylock);return NULL;}int main() {pthread_t t1, t2;Mutex_Init(&mylock);pthread_create(&t1, NULL, worker, (void*)1);pthread_create(&t2, NULL, worker, (void*)2);pthread_join(t1, NULL);pthread_join(t2, NULL);return 0;}
Mutex Structuretypedef struct {atomic_flag flag;} Mutex;
atomic_flag is a special atomic boolean type.void Mutex_Init(Mutex* m) {atomic_flag_clear(&m->flag); // initially unlocked}
atomic_flag_clear sets the flag to 0 (unlocked).void Mutex_Lock(Mutex* m) {while (atomic_flag_test_and_set(&m->flag)) {// Busy wait (spinning)}}
atomic_flag_test_and_set(&m->flag) does two things atomically:1 (locked) if it was 0.1 → the function returns true → thread cannot enter.while loop keeps running → this is called busy waiting or spinning.0 (unlocked), the thread acquires the lock and exits the loop.🔹 Analogy
void Mutex_Unlock(Mutex* m) {atomic_flag_clear(&m->flag);}
0 (unlocked).void* worker(void* arg) {Mutex_Lock(&mylock);printf("Thread %ld entered critical section\n", (long)arg);for (volatile int i = 0; i < 100000000; i++); // simulate workprintf("Thread %ld leaving critical section\n", (long)arg);Mutex_Unlock(&mylock);return NULL;}
pthread_t t1, t2;Mutex_Init(&mylock);pthread_create(&t1, NULL, worker, (void*)1);pthread_create(&t2, NULL, worker, (void*)2);pthread_join(t1, NULL);pthread_join(t2, NULL);
| Feature | Description |
|---|---|
| Type | Spinlock mutex |
| Locking behavior | Busy wait (spins until lock is free) |
| CPU usage | High if waiting, because thread keeps checking in a loop |
| Atomic operation | atomic_flag_test_and_set ensures thread-safe locking |
| Unlocking | Clears the flag, allowing next thread to acquire |
🔹 Visual Analogy
Thread 1: acquires lock -> executes critical sectionThread 2: sees lock taken -> keeps spinning (busy wait)Thread 1: finishes -> unlocksThread 2: grabs lock -> executes critical section
Quick Links
Legal Stuff





