Lecture
Mutex (eng. Mutex , from mutual exclusion - “mutual exclusion”) is an analogue of a single semaphore that serves in programming for synchronization of simultaneously running threads.
A mutex differs from a semaphore in that only the thread that owns it can release it, i.e. transfer to the marked state. Mutexes are one of the variants of semaphore mechanisms for organizing mutual exclusion. They are implemented in many operating systems, their main purpose is the organization of mutual exclusion for threads from the same or from different processes.
Mutexes are simplest binary semaphores that can be in one of two states — marked or unmarked (opened and closed, respectively). When a thread belonging to any process becomes the owner of a mutex object, the latter is transferred to the unmarked state. If the task releases the mutex, its state becomes marked.
The task of the mutex is to protect the object from access to it by other threads other than the one that has taken over the mutex. At any given time, only one thread can own an object protected by a mutex. If another thread needs access to a variable protected by a mutex, then this thread is blocked until the mutex is released.
The purpose of using mutexes is to protect data from damage due to asynchronous changes (race conditions), but other problems can arise, such as deadlock (clinch).
The Win32 API in Windows has two implementations of mutexes - the actual mutexes [1] , which have names and are available for use between different processes, and critical sections [2] , which can be used only within one process. For each of these two types of mutexes, their own capture and release functions are used.
If possible, the critical section in Windows is blocked without using the kernel mode call (similar to the spinlock), but if such a lock is impossible, the thread requests the kernel.
A mutex in the standard Pthreads library can be used in one process or in different ones, but in any case, all using processes need access to the memory in which it is located. Such a mutex can have one of the following types [3] :
The latest C standard ( ISO / IEC 9899: 2011 [4] ) defines the type of mtx_t and the functions for working with it, which should be available if the macro __STDC_NO_THREADS__ was not defined by the compiler. The semantics and properties of mutexes generally coincide with the POSIX standard:
The possibility of using mutexes in shared memory of various processes in the C11 standard is not considered.
The C ++ language standard ( ISO / IEC 14882: 2011 [5] ) defines various classes of mutexes:
Note the Boost library, which provides:
Comments
To leave a comment
Operating Systems and System Programming
Terms: Operating Systems and System Programming