Mutex: Difference between revisions
Content added Content deleted
(Added some code. Add some for other languages...) |
(Ada's implementation of mutex) |
||
Line 19: | Line 19: | ||
There exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. |
There exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. |
||
=Sample implementations / APIs= |
|||
=APIs=== |
|||
=={{header|Ada}}== |
|||
[[Ada]] provides higher-level concurrency primitives, which are complete in the sense that they also allow implementations of the lower-level ones, like mutex. Here is an implementation of a plain non-reentrant mutex based on protected objects. |
|||
The mutex interface: |
|||
<ada> |
|||
protected type Mutex is |
|||
entry Seize; |
|||
procedure Release; |
|||
private |
|||
Owned : Boolean := False; |
|||
end Mutex; |
|||
</ada> |
|||
The implementation of: |
|||
<ada> |
|||
protected body Mutex is |
|||
entry Seize when not Owned is |
|||
begin |
|||
Owned := True; |
|||
end Seize; |
|||
procedure Release is |
|||
begin |
|||
Owned := False; |
|||
end Release; |
|||
end Mutex; |
|||
</ada> |
|||
Use: |
|||
<ada> |
|||
declare |
|||
M : Mutex; |
|||
begin |
|||
M.Seize; -- Wait infinitely for the mutex to be free |
|||
... -- Critical code |
|||
M.Release; -- Release the mutex |
|||
... |
|||
select |
|||
M.Seize; -- Wait no longer than 0.5s |
|||
or delay 0.5; |
|||
raise Timed_Out; |
|||
end select; |
|||
... -- Critical code |
|||
M.Release; -- Release the mutex |
|||
end; |
|||
</ada> |
|||
It is also possible to implement mutex as a monitor task. |
|||
=={{header|C}}== |
=={{header|C}}== |
||
{{works with|Win32}} |
{{works with|Win32}} |