|
|
|
|
|
- Overview
- Principle
- How to implement a mutex?
- Steps:
- Remarks
- Functions for managing a mutex
Managing mutexes in threads
A mutex is used to limit the simultaneous execution of a code (procedure, line of code, etc.) to one thread at a given time. A mutex can be shared between several applications. Remark: Other systems can also be used to protect a piece of code: - semaphores are used to limit the simultaneous execution of a code (procedure, line of code, etc.) to one or more threads at a given time. A semaphore can be shared between several applications.
- critical sections are used to limit the simultaneous execution of a code (procedure, line of code, etc.) to one thread at a given time in a single application.
The mutex was created by MutexCreate. - Thread n°1 executes function MutexStart: no thread is currently present in the mutex.
- Thread #1 runs the code section protected by the mutex.
- While thread #1 executes the mutex-protected code, thread #2 executes the MutexStart function: as the mutex-protected code is already being executed by thread #1, thread #2 waits for the mutex to be released.
- Thread n°1 executes function MutexEnd: no more threads execute the mutex code.
- Thread #2 can run the code protected by the mutex.
- Thread n°2 executes function MutexEnd: no more threads execute the mutex code.
How to implement a mutex? Steps: The different steps for implementing a mutex are as follows: - Creating a mutex with MutexCreate. The mutex is associated with a name.
- Calling MutexStart before the code section to protect.
- Calling MutexEnd to define the code section to protect. The lines of code after MutexEnd will no longer be protected.
- Destroying the mutex with MutexDestroy.
Remarks - The code sections protected by a mutex must be as short as possible and they must only affect the "critical" processes.
- When a thread is pending, the resources of the processor are not used.
- A mutex can be applied to the main thread and to the secondary threads (created by ThreadExecute). You must avoid locking the main thread. Indeed, if the main thread is locked (pending), the application cannot be run anymore.
- MutexStart and MutexEnd must be used in the same process (in a procedure for example).
- A mutex can be shared (or not) between the different applications run on the computer. When creating a mutex, specify how it will be shared (MutexCreate).
Functions for managing a mutex The following WLanguage functions are used to manage mutexes:
This page is also available for…
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|