Skip to content
serhij.zolotukhin edited this page Dec 7, 2025 · 1 revision

THEORY

Mutex (or Lock)
Mutex (or Lock)
(англ. mutex, от mutual exclusion — «взаимное исключение») — аналог одноместного семафора
Мьютекс отличается от семафора тем, что только владеющий им поток может его освободить
 
In computer science, a lock or mutex (from mutual exclusion) 
is a synchronization mechanism for enforcing limits on access to a resource 
in an environment where there are many threads of execution. 
 
A lock is designed to enforce a mutual exclusion concurrency control policy

API

Pthread API blocking Mutexes
#include <pthread.h>
int pthread_mutex_lock (pthread_mutex_t *mutex);
int pthread_mutex_unlock (pthread_mutex_t *mutex);
Pthread API Nonblocking Mutex
#include <pthread.h>
int pthread_mutex_trylock(pthread_mutex_t *mutex);

IMPLEMENTATION IN LINUX

Futex (or Lightweight Mutex) at Userspace
Futex (Short for Fast Userspace Mutex) -
is a kernel system call that programmers can use to implement basic locking, 
or as a building block for higher-level locking abstractions such as semaphores 
and POSIX mutexes or condition variables.
 
A futex consists of a kernelspace wait queue that is attached to an aligned integer in userspace. 
Multiple processes or threads operate on the integer entirely in userspace 
(using atomic operations to avoid interfering with one another), 
and only resort to relatively expensive system calls to request operations on the wait queue 
(for example to wake up waiting processes, or to put the current process on the wait queue).               
kernel mutex at Kernel space
/kernel/locking/mutex.c
 
These locks use a three state atomic counter (->count) to represent the different possible
transitions that can occur during the lifetime of a lock:
 
    1: unlocked
    0: locked, no waiters
    negative: locked, with potential waiters
URLs

My side bar

Clone this wiki locally