![]() |
CITS2002 Systems Programming |
← prev | next → | ![]() |
![]() |
|||
Pthreads functions to manage mutexesCreating and destroying:
Mutex variables must be declared with type pthread_mutex_t,
and be initialized before being used.
A mutex is initially unlocked.
There are two ways to initialize a mutex variable:
pthread_mutex_destroy() may be used when a mutex object which is no longer needed (or, like dynamic memory, will be deallocated when the whole process terminates). Locking and unlocking:
The pthread_mutex_lock() function acquires a lock on the specified mutex variable.
If the mutex is already locked by another thread,
this call will block the calling thread until the mutex is unlocked.
pthread_mutex_trylock() will attempt to lock a mutex. However, if the mutex is already locked, the routine will return immediately with a busy error code. This function may be useful in preventing deadlock conditions. pthread_mutex_unlock() will unlock a mutex if called by the owning thread, after it has completed its use of protected data. An error will be returned if:
There is nothing "magical" about mutexes, they are just an agreement between participating threads. It is up to the programmer to ensure that all necessary threads make the mutex lock and unlock calls correctly.
CITS2002 Systems Programming, Lecture 21, p4, 10th October 2023.
|