Mutex: Difference between revisions

1,071 bytes added ,  15 years ago
Ada's implementation of mutex
(Added some code. Add some for other languages...)
(Ada's implementation of mutex)
Line 19:
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}}==
{{works with|Win32}}