Mutex: Difference between revisions

no edit summary
(→‎POSIX: fixing and adding)
No edit summary
Line 25:
 
The mutex interface:
<lang ada>
protected type Mutex is
entry Seize;
Line 32:
Owned : Boolean := False;
end Mutex;
</adalang>
The implementation of:
<lang ada>
protected body Mutex is
entry Seize when not Owned is
Line 45:
end Release;
end Mutex;
</adalang>
Here the entry Seize has a queue of the [[task]]s waiting for the mutex. The entry's barrier is closed when Owned is true. So any task calling to the entry will be queued. When the barrier is open the first task from the queue executes the entry and Owned becomes false closing the barrier again. The procedure Release simply sets Owned to false. Both Seize and Release are protected actions which execution causes reevaluation of all barriers, in this case one of Seize.
 
Use:
<lang ada>
declare
M : Mutex;
Line 65:
M.Release; -- Release the mutex
end;
</adalang>
It is also possible to implement mutex as a monitor task.
=={{header|C}}==
Line 72:
{{works with|Win32}}
To create a mutex operating system "object":
<lang c>
HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
</clang>
To lock the mutex:
<lang c>
WaitForSingleObject(hMutex, INFINITE);
</clang>
To unlock the mutex
<lang c>
ReleaseMutex(hMutex);
</clang>
When the program is finished with the mutex:
<lang c>
CloseHandle(hMutex);
</clang>
 
===POSIX===
Line 93:
Creating a mutex:
 
<lang c>#include <pthread.h>
 
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;</clang>
 
Or:
 
<lang c>pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);</clang>
 
Locking:
 
<lang c>int success = pthread_mutex_lock(&mutex);</clang>
 
Unlocking:
 
<lang c>int success = pthread_mutex_unlock(&mutex);</clang>
 
Trying to lock (but do not wait if it can't)
 
<lang c>int success = pthread_mutex_trylock(&mutex);</clang>
 
=={{header|C++}}==