М'ютекс (Mutex)
Примітив синхронізації, що забезпечує взаємне виключення: лише один потік може володіти ресурсом.
A Mutex (short for Mutual Exclusion) is a locking mechanism used to manage access to a shared resource. Only one thread can 'own' a mutex at a time. If a thread wants to use a resource, it must 'lock' the mutex. If the mutex is already locked, the thread's execution is typically blocked until the owner 'unlocks' it.
graph LR
Center["М'ютекс (Mutex)"]:::main
Rel_semaphore["semaphore"]:::related -.-> Center
click Rel_semaphore "/terms/semaphore"
classDef main fill:#7c3aed,stroke:#8b5cf6,stroke-width:2px,color:white,font-weight:bold,rx:5,ry:5;
classDef pre fill:#0f172a,stroke:#3b82f6,color:#94a3b8,rx:5,ry:5;
classDef child fill:#0f172a,stroke:#10b981,color:#94a3b8,rx:5,ry:5;
classDef related fill:#0f172a,stroke:#8b5cf6,stroke-dasharray: 5 5,color:#94a3b8,rx:5,ry:5;
linkStyle default stroke:#4b5563,stroke-width:2px;
🧠 Перевірка знань
🧒 Простими словами
Уявіть туалетну кабінку в поїзді. Вона має замок. Якщо хтось зайшов і закрив замок (lock), ніхто інший не може зайти, доки людина всередині не відкриє замок (unlock) і не вийде.
🤓 Expert Deep Dive
Існують різні типи м'ютексів: рекурсивні (reentrant) дозволяють тому ж потоку захоплювати замок кілька разів; timed mutex дозволяє чекати замок лише певний час. Важливою проблемою є Priority Inversion, коли низькопріоритетний потік тримає м'ютекс, блокуючи високопріоритетний. Рішення: Priority Inheritance Protocol. На Linux реалізовані через futex (fast userspace mutex).