Mutex: Difference between revisions

411 bytes added ,  15 years ago
Added some code. Add some for other languages...
m (Race condition link)
(Added some code. Add some for other languages...)
Line 5:
Mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can be constructed already with two tasks and two mutexes. Entering the deadlock is usually aggravated by a [[race condition]] state, which leads to sporadic hangups, very difficult to track down.
 
==Variants of mutexes==
 
===Global and local mutexes===
Usually [[OS]] provides various implementations of mutexes corresponding to the variants of [[task]]s available in the [[OS]]. For example, system-wide mutexes can be used by [[process]]es. Local mutexes can be used only by [[threads]] etc. This distinction is maintained because, depending on the hardware, seizing a global mutex might be thousand times slower than seizing a local one.
 
===Reentrant mutex===
A reentrant mutex can be seized by the same [[task]] multiple times. Each seizing of the mutex is matched by releasing it, in order to allow other task to seize it.
 
===Read write mutex===
A read write mutex can be seized at two levels for ''read'' and for ''write''. The mutex can be seized for ''read'' by any number of tasks. Only one task may seize it '''write''. Read write mutex are usually used to protect resources which can be accessed in a mutable and immutable ways. Immutable (read) access is granted concurrently for many tasks because they do not change the resource state. Read write mutexes can be reentrant, global or local. Further, promotion operations may be provided, that's when a [[task]] that have seized the mutex for ''write'' releases it keeping seized for ''read''. Note that the reverse operation is potentially deadlocking and requires some additional access policy control.
 
==Deadlock prevention==
There exists a simple technique of deadlock prevention when mutexes are seized in some fixed order.
 
=APIs===
=={{header|C}}==
{{works with|Win32}}
To create a mutex operating system "object":
<cpp>
HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
</cpp>
To lock the mutex:
<cpp>
WaitForSingleObject(hMutex, INFINITE);
</cpp>
To unlock the mutex
<cpp>
ReleaseMutex(hMutex);
</cpp>
When the program is finished with the mutex:
<cpp>
CloseHandle(hMutex);
</cpp>
=={{header|C++}}==
{{works with|Win32}}
See C example