Книга: 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.

Оглавление книги


Генерация: 0.052. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз