Книга: Microsoft Windows Embedded CE 6.0 Exam Preparation Kit
Critical Sections
Critical Sections
Critical sections are objects that synchronize threads and guard access to resources within a single process. A critical section cannot be shared between processes. To access a resource protected by a critical section, a thread calls the EnterCriticalSection function. This function blocks the thread until the critical section is available.
In some situations, blocking the thread execution might not be efficient. For example, if you want to use an optional resource that might never be available, calling the EnterCriticalSection function blocks your thread and consumes kernel resources without performing any processing on the optional resource. It is more efficient in this case to use a critical section without blocking by calling the TryEnterCriticalSection function. This function attempts to grab the critical section and returns immediately if the critical section cannot be used. The thread can then continue along an alternative code path, such as to prompt the user for input or to plug in a missing device.
Having obtained the critical section object through EnterCriticalSection or TryEnterCriticalSection, the thread enjoys exclusive access to the resource. No other thread can access this resource until the current thread calls the LeaveCriticalSection function to release the critical section object. Among other things, this mechanism highlights why you should not use the TerminateThread function to terminate threads. TerminateThread does not perform cleanup. If the terminated thread owned a critical section, the protected resource becomes unusable until the user restarts the application.
Table 3-11 lists the most important functions that you can use to work with critical section objects for thread synchronization purposes.
Table 3-11 Critical Section API
Function | Description |
---|---|
InitializeCriticalSection | Create and initialize a critical section object. |
DeleteCriticalSection | Destroy a critical section object. |
EnterCriticalSection | Grab a critical section object. |
TryEnterCriticalSection | Try to grab a critical section object. |
LeaveCriticalSection | Release a critical section object. |
- 15.5 Critical Section Revisited
- 3.1 Invariants, critical sections,and predicates
- Experiment with Multithreaded Applications and Critical Sections
- 17.3.4. Critical Section Management
- Использование объектов CRITICAL_SECTION для защиты разделяемыхпеременных
- Сравнительный обзор: мьютексы и объекты CRITICAL_SECTION
- Дополнительные рекомендации относительно использования мьютексов и объектов CRITICAL_SECTION
- Достоинства и недостатки объектов CRITICAL_SECTION
- Параллельные секции и директива parallel sections
- Листинг 4.6. (critical_section.c) Защита банковской транзакции с помощью критической секции
- 7.4.4 Marking Sections of the Outline