| Previous | Main | Next | Site Index | Download | Disclaimer | Privacy |


 

 

 

Windows Process, thread and synchronization: Functions used in program examples of ModuleR, ModuleS, ModuleT, ModuleU, ModuleV and ModuleAA, wherever applicable.

 

To learn about function you can jump to Module 4.

 

Index

 

EnterCriticalSection()

InitializeCriticalSectionAndSpinCount()

LeaveCriticalSection()

DeleteCriticalSection()

Module32First()

Module32Next()

MsgWaitForMultipleObjects()

CreateEvent()

ResetEvent()

SetEvent()

EnumProcesses()

OpenProcess()

EnumProcessModules()

GetModuleBaseName()

GetModuleFileNameEx()

CommandLineToArgvW()

CreateMutex()

ReleaseMutex()

CreateSemaphore()

ReleaseSemaphore()

OpenSemaphorev()

CreateNamedPipe()

CreateFileMapping()

 

 

 EnterCriticalSection()

 

Item

Description

Function

EnterCriticalSection().

Use

Waits for ownership of the specified critical section object. The function returns when the calling thread is granted ownership.

Prototype

void EnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection);

Parameters

lpCriticalSection

[in, out] Pointer to the critical section object.

Return value

This function does not return a value.  This function can raise EXCEPTION_POSSIBLE_DEADLOCK if the critical section is corrupt or deadlock detection is enabled. Do not handle this exception; either continue execution or debug the application.

For Windows 2000/NT:  In low memory situations, EnterCriticalSection() can raise an exception. To avoid problems, use structured exception handling, or call the InitializeCriticalSectionAndSpinCount() function to pre-allocate the event used by EnterCriticalSection() instead of calling the InitializeCriticalSection() function, which forces EnterCriticalSection() to allocate the event.

Include file

<windows.h>

Remark

See below.

 

Table 1.

 

Remarks

 

The threads of a single process can use a critical section object for mutual-exclusion synchronization. The process is responsible for allocating the memory used by a critical section object, which it can do by declaring a variable of type CRITICAL_SECTION. Before using a critical section, some thread of the process must call InitializeCriticalSection() or InitializeCriticalSectionAndSpinCount() to initialize the object.

To enable mutually exclusive access to a shared resource, each thread calls the EnterCriticalSection() or TryEnterCriticalSection() function to request ownership of the critical section before executing any section of code that accesses the protected resource. The difference is that TryEnterCriticalSection() returns immediately, regardless of whether it obtained ownership of the critical section, while EnterCriticalSection() blocks until the thread can take ownership of the critical section. When it has finished executing the protected code, the thread uses the LeaveCriticalSection() function to relinquish ownership, enabling another thread to become owner and access the protected resource. The thread must call LeaveCriticalSection() once for each time that it entered the critical section. The thread enters the critical section each time EnterCriticalSection() and TryEnterCriticalSection() succeed.

After a thread has ownership of a critical section, it can make additional calls to EnterCriticalSection() or TryEnterCriticalSection() without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns.

Any thread of the process can use the DeleteCriticalSection() function to release the system resources that were allocated when the critical section object was initialized. After this function has been called, the critical section object can no longer be used for synchronization.

If a thread terminates while it has ownership of a critical section, the state of the critical section is undefined.  If a critical section is deleted while it is still owned, the state of the threads waiting for ownership of the deleted critical section is undefined.

 

 

InitializeCriticalSectionAndSpinCount()

 

Item

Description

Function

InitializeCriticalSectionAndSpinCount().

Use

Initializes a critical section object and sets the spin count for the critical section.

Prototype

BOOL InitializeCriticalSectionAndSpinCount(

  LPCRITICAL_SECTION lpCriticalSection,

  DWORD dwSpinCount);

Parameters

lpCriticalSection

[in, out] Pointer to the critical section object.

 

dwSpinCount

[in] Spin count for the critical section object. On single-processor systems, the spin count is ignored and the critical section spin count is set to 0. On multiprocessor systems, if the critical section is unavailable, the calling thread will spin dwSpinCount times before performing a wait operation on a semaphore associated with the critical section. If the critical section becomes free during the spin operation, the calling thread avoids the wait operation.

Windows 2000:  If the high-order bit is set, the function pre-allocates the event used by the EnterCriticalSection() function. Do not set this bit if you are creating a large number of critical section objects, because it will consume a significant amount of non-paged pool. This flag is not necessary on Windows XP and later, and it is ignored.

Return value

If the function succeeds, the return value is nonzero.  If the function fails, the return value is zero. To get extended error information, call GetLastError().  For Windows Me/98/95:  This function has no return value. If the function fails, it will raise an exception.

Include file

<windows.h>

Remark

See below.

 

Table 2.

 

Remarks

 

The threads of a single process can use a critical section object for mutual-exclusion synchronization. There is no guarantee about the order in which threads will obtain ownership of the critical section, however, the system will be fair to all threads. The process is responsible for allocating the memory used by a critical section object, which it can do by declaring a variable of type CRITICAL_SECTION. Before using a critical section, some thread of the process must call the InitializeCriticalSection() or InitializeCriticalSectionAndSpinCount() function to initialize the object. You can subsequently modify the spin count by calling the SetCriticalSectionSpinCount() function. After a critical section object has been initialized, the threads of the process can specify the object in the EnterCriticalSection(), TryEnterCriticalSection(), or LeaveCriticalSection() function to provide mutually exclusive access to a shared resource. For similar synchronization between the threads of different processes, use a mutex object. A critical section object cannot be moved or copied. The process must also not modify the object, but must treat it as logically opaque. Use only the critical section functions to manage critical section objects. When you have finished using the critical section, call the DeleteCriticalSection() function.

A critical section object must be deleted before it can be reinitialized. Initializing a critical section that has already been initialized results in undefined behavior. The spin count is useful for critical sections of short duration that can experience high levels of contention. Consider a worst-case scenario, in which an application on an Symmetric Multi Processor (SMP) system has two or three threads constantly allocating and releasing memory from the heap. The application serializes the heap with a critical section. In the worst-case scenario, contention for the critical section is constant, and each thread makes an expensive call to the WaitForSingleObject() function. However, if the spin count is set properly, the calling thread will not immediately call WaitForSingleObject() when contention occurs. Instead, the calling thread can acquire ownership of the critical section if it is released during the spin operation. You can improve performance significantly by choosing a small spin count for a critical section of short duration. The heap manager uses a spin count of roughly 4000 for its per-heap critical sections. This gives great performance and scalability in almost all worst-case scenarios. To compile an application that uses this function, define the _WIN32_WINNT macro as 0x0403 or later.

 

LeaveCriticalSection()

 

Item

Description

Function

LeaveCriticalSection().

Use

Releases ownership of the specified critical section object.

Prototype

void LeaveCriticalSection(LPCRITICAL_SECTION lpCriticalSection);

Parameters

lpCriticalSection

[in, out] Pointer to the critical section object.

Return value

This function does not return a value.

Include file

<windows.h>

Remark

See below.

 

Table 3.

 

Remarks

 

The threads of a single process can use a critical-section object for mutual-exclusion synchronization. The process is responsible for allocating the memory used by a critical-section object, which it can do by declaring a variable of type CRITICAL_SECTION. Before using a critical section, some thread of the process must call the InitializeCriticalSection() or InitializeCriticalSectionAndSpinCount() function to initialize the object. A thread uses the EnterCriticalSection() or TryEnterCriticalSection() function to acquire ownership of a critical section object. To release its ownership, the thread must call LeaveCriticalSection once for each time that it entered the critical section. If a thread calls LeaveCriticalSection() when it does not have ownership of the specified critical section object, an error occurs that may cause another thread using EnterCriticalSection() to wait indefinitely.

Any thread of the process can use the DeleteCriticalSection() function to release the system resources that were allocated when the critical section object was initialized. After this function has been called, the critical section object can no longer be used for synchronization.

 

 

DeleteCriticalSection()

 

Item

Description

Function

DeleteCriticalSection().

Use

To release all resources used by an unowned critical section object.

Prototype

void DeleteCriticalSection(LPCRITICAL_SECTION lpCriticalSection);

Parameters

lpCriticalSection

[in, out] Pointer to the critical section object. The object must have been previously initialized with the InitializeCriticalSection() function.

Return value

This function does not return a value.

Include file

<windows.h>

Remark

Deleting a critical section object releases all system resources used by the object.  After a critical section object has been deleted, do not reference the object in any function that operates on critical sections (such as EnterCriticalSection(), TryEnterCriticalSection(), and LeaveCriticalSection()) other than InitializeCriticalSection() and InitializeCriticalSectionAndSpinCount(). If you attempt to do so, memory corruption and other unexpected errors can occur.

If a critical section is deleted while it is still owned, the state of the threads waiting for ownership of the deleted critical section is undefined.

 

Table 4.

 

Module32First()

 

Item

Description

Function

Module32First().

Use

To retrieve information about the first module associated with a process.

Prototype

BOOL WINAPI Module32First(HANDLE hSnapshot, LPMODULEENTRY32 lpme);

Parameters

hSnapshot

[in] Handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot() function.

 

lpme

[in, out] Pointer to a MODULEENTRY32 structure.

Return value

Returns TRUE if the first entry of the module list has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError() function if no modules exist or the snapshot does not contain module information.

Include file

<tlhelp32.h>

Remark

The calling application must set the dwSize member of MODULEENTRY32 to the size, in bytes, of the structure.  To retrieve information about other modules associated with the specified process, use the Module32Next() function.

 

Table 5.

 

 

Module32Next()

 

Item

Description

Function

Module32Next().

Use

To retrieve information about the next module associated with a process or thread.

Prototype

BOOL WINAPI Module32Next(HANDLE hSnapshot, LPMODULEENTRY32 lpme);

Parameters

hSnapshot

[in] Handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot() function.

 

lpme

[out] Pointer to a MODULEENTRY32 structure.

Return value

Returns TRUE if the next entry of the module list has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError() function if no more modules exist.

Include file

<tlhelp32.h>

Remark

To retrieve information about first module associated with a process, use the Module32First() function.

 

Table 6.

 

 

MsgWaitForMultipleObjects()

 

Item

Description

Function

MsgWaitForMultipleObjects().

Use

Returns when any one or all of the specified objects are in the signaled state or the time-out interval elapses. The objects can include input event objects, which you specify using the dwWakeMask parameter.  To enter an alertable wait state, use the MsgWaitForMultipleObjectsEx() function.

Prototype

DWORD MsgWaitForMultipleObjects(

  DWORD nCount,

  const HANDLE* pHandles,

  BOOL bWaitAll,

  DWORD dwMilliseconds,

  DWORD dwWakeMask);

Parameters

See below.

Return value

See below.

Include file

<windows.h>

Remark

See below.

 

Table 7.

 

Parameters

 

nCount

[in] Number of object handles in the array pointed to by pHandles. The maximum number of object handles is MAXIMUM_WAIT_OBJECTS minus one.

 

pHandles

[in] Pointer to an array of object handles. For a list of the object types whose handles can be specified, see the following Remarks section. The array can contain handles of objects of different types. It may not contain multiple copies of the same handle.  If one of these handles is closed while the wait is still pending, the function's behavior is undefined.

The handles must have the SYNCHRONIZE access right.  For Windows Me/98/95:  No handle may be a duplicate of another handle created using DuplicateHandle().

 

bWaitAll

[in] If this parameter is TRUE, the function returns when the states of all objects in the pHandles array have been set to signaled and an input event has been received. If this parameter is FALSE, the function returns when the state of any one of the objects is set to signaled or an input event has been received. In this case, the return value indicates the object whose state caused the function to return.

 

dwMilliseconds

[in] Time-out interval, in milliseconds. The function returns if the interval elapses, even if the criteria specified by the bWaitAll or dwWakeMask parameter have not been met. If dwMilliseconds is zero, the function tests the states of the specified objects and returns immediately. If dwMilliseconds is INFINITE, the function's time-out interval never elapses.

 

dwWakeMask

[in] Input types for which an input event object handle will be added to the array of object handles. This parameter can be any combination of the following values.

 

Value

Meaning

QS_ALLEVENTS

An input, WM_TIMER, WM_PAINT, WM_HOTKEY, or posted message is in the queue. This value is a combination of QS_INPUT, QS_POSTMESSAGE, QS_TIMER, QS_PAINT, and QS_HOTKEY.

QS_ALLINPUT

Any message is in the queue. This value is a combination of QS_INPUT, QS_POSTMESSAGE, QS_TIMER, QS_PAINT, QS_HOTKEY, and QS_SENDMESSAGE.

QS_ALLPOSTMESSAGE

A posted message is in the queue.

This value is cleared when you call GetMessage() or PeekMessage() without filtering messages.

QS_HOTKEY

A WM_HOTKEY message is in the queue.

QS_INPUT

An input message is in the queue. This value is a combination of QS_MOUSE and QS_KEY.

Windows 2003 Server and Windows XP:  This value also includes QS_RAWINPUT.

QS_KEY

A WM_KEYUP, WM_KEYDOWN, WM_SYSKEYUP, or WM_SYSKEYDOWN message is in the queue.

QS_MOUSE

A WM_MOUSEMOVE message or mouse-button message (WM_LBUTTONUP, WM_RBUTTONDOWN, and so on).

This value is a combination of QS_MOUSEMOVE and QS_MOUSEBUTTON.

QS_MOUSEBUTTON

A mouse-button message (WM_LBUTTONUP, WM_RBUTTONDOWN, and so on).

QS_MOUSEMOVE

A WM_MOUSEMOVE message is in the queue.

QS_PAINT

A WM_PAINT message is in the queue.

QS_POSTMESSAGE

A posted message is in the queue. This value is cleared when you call GetMessage() or PeekMessage(), whether or not you are filtering messages.

QS_RAWINPUT

A raw input message is in the queue.  For Windows 2000/NT and Windows Me/98/95:  This value is not supported.

QS_SENDMESSAGE

A message sent by another thread or application is in the queue.

QS_TIMER

A WM_TIMER message is in the queue.

 

Table 8

 

Return Values

 

If the function succeeds, the return value indicates the event that caused the function to return. It can be one of the following values.

 

Return code

Description

WAIT_OBJECT_0 to (WAIT_OBJECT_0 + nCount 1)

If bWaitAll is TRUE, the return value indicates that the state of all specified objects is signaled. If bWaitAll is FALSE, the return value minus WAIT_OBJECT_0 indicates the pHandles array index of the object that satisfied the wait.

WAIT_OBJECT_0 + nCount

New input of the type specified in the dwWakeMask parameter is available in the thread's input queue. Functions such as PeekMessage(), GetMessage(), and WaitMessage() mark messages in the queue as old messages. Therefore, after you call one of these functions, a subsequent call to MsgWaitForMultipleObjects() will not return until new input of the specified type arrives.

This value is also returned upon the occurrence of a system event that requires the thread's action, such as foreground activation. Therefore, MsgWaitForMultipleObjects() can return even though no appropriate input is available and even if dwWakeMask is set to 0. If this occurs, call GetMessage() or PeekMessage() to process the system event before trying the call to MsgWaitForMultipleObjects() again.

WAIT_ABANDONED_0 to (WAIT_ABANDONED_0 + nCount 1)

If bWaitAll is TRUE, the return value indicates that the state of all specified objects is signaled and at least one of the objects is an abandoned mutex object. If bWaitAll is FALSE, the return value minus WAIT_ABANDONED_0 indicates the pHandles array index of an abandoned mutex object that satisfied the wait.

WAIT_TIMEOUT

The time-out interval elapsed and the conditions specified by the bWaitAll and dwWakeMask parameters were not satisfied.

 

Table 9

 

If the function fails, the return value is WAIT_FAILED. To get extended error information, call GetLastError().

 

Remarks

 

The MsgWaitForMultipleObjects() function determines whether the wait criteria have been met. If the criteria have not been met, the calling thread enters the wait state. It uses no processor time while waiting for the conditions of the wait criteria to be met.

When bWaitAll is TRUE, the function does not modify the states of the specified objects until the states of all objects have been set to signaled. For example, a mutex can be signaled, but the thread does not get ownership until the states of the other objects have also been set to signaled. In the meantime, some other thread may get ownership of the mutex, thereby setting its state to non-signaled.

 

When bWaitAll is TRUE, the function's wait is completed only when the states of all objects have been set to signaled and an input event has been received. Therefore, setting bWaitAll to TRUE prevents input from being processed until the state of all objects in the pHandles array have been set to signaled. For this reason, if you set bWaitAll to TRUE, you should use a short timeout value in dwMilliseconds. If you have a thread that creates windows waiting for all objects in the pHandles array, including input events specified by dwWakeMask, with no timeout interval, the system will deadlock. This is because threads that create windows must process messages. DDE sends message to all windows in the system. Therefore, if a thread creates windows, do not set the bWaitAll parameter to TRUE in calls to MsgWaitForMultipleObjects() made from that thread.

 

Note:  MsgWaitForMultipleObjects() does not return if there is unread input of the specified type in the message queue after the thread has called a function to check the queue. This is because functions such as PeekMessage(), GetMessage(), GetQueueStatus(), and WaitMessage() check the queue and then change the state information for the queue so that the input is no longer considered new. A subsequent call to MsgWaitForMultipleObjects() will not return until new input of the specified type arrives. The existing unread input (received prior to the last time the thread checked the queue) is ignored. The function modifies the state of some types of synchronization objects. Modification occurs only for the object or objects whose signaled state caused the function to return. For example, the count of a semaphore object is decreased by one. When bWaitAll is FALSE, and multiple objects are in the signaled state, the function chooses one of the objects to satisfy the wait; the states of the objects not selected are unaffected. The MsgWaitForMultipleObjects() function can specify handles of any of the following object types in the pHandles array:

 

          Change notification

          Console input

          Event

          Job

          Memory resource notification

          Mutex

          Process

          Semaphore

          Thread

          Waitable timer

 

The QS_ALLPOSTMESSAGE and QS_POSTMESSAGE flags differ in when they are cleared. QS_POSTMESSAGE is cleared when you call GetMessage() or PeekMessage(), whether or not you are filtering messages. QS_ALLPOSTMESSAGE is cleared when you call GetMessage() or PeekMessage() without filtering messages (wMsgFilterMin and wMsgFilterMax are 0). This can be useful when you call PeekMessage() multiple times to get messages in different ranges.

 

CreateEvent()

 

Item

Description

Function

CreateEvent().

Use

To create or opens a named or unnamed event object.

Prototype

HANDLE CreateEvent(

  LPSECURITY_ATTRIBUTES lpEventAttributes,

  BOOL bManualReset,

  BOOL bInitialState,

  LPCTSTR lpName);

Parameters

See below.

Return value

If the function succeeds, the return value is a handle to the event object. If the named event object existed before the function call, the function returns a handle to the existing object and GetLastError() returns ERROR_ALREADY_EXISTS.  If the function fails, the return value is NULL. To get extended error information, call GetLastError().

Include file

<windows.h>

Remark

Implemented as Unicode and ANSI versions. Note that Unicode support on Windows Me/98/95 requires Microsoft Layer for Unicode.  More remarks below.

 

Table 10.

 

Parameters

 

lpEventAttributes

[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpEventAttributes is NULL, the handle cannot be inherited.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the new event. If lpEventAttributes is NULL, the event gets a default security descriptor. The ACLs in the default security descriptor for an event come from the primary or impersonation token of the creator.

 

bManualReset

[in] If this parameter is TRUE, the function creates a manual-reset event object which requires use of the ResetEvent() function set the state to non-signaled. If this parameter is FALSE, the function creates an auto-reset event object, and system automatically resets the state to non-signaled after a single waiting thread has been released.

 

bInitialState

[in] If this parameter is TRUE, the initial state of the event object is signaled; otherwise, it is non-signaled.

 

lpName

[in] Pointer to a null-terminated string specifying the name of the event object. The name is limited to MAX_PATH characters. Name comparison is case sensitive.

If lpName matches the name of an existing named event object, this function requests the EVENT_ALL_ACCESS access right. In this case, the bManualReset and bInitialState parameters are ignored because they have already been set by the creating process. If the lpEventAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.

If lpName is NULL, the event object is created without a name. If lpName matches the name of an existing semaphore, mutex, waitable timer, job, or file-mapping object, the function fails and the GetLastError() function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same name space.

Terminal Services:  The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session name space. The remainder of the name can contain any character except the backslash character (\).

 

For Windows XP Home Edition:  Fast user switching is implemented using Terminal Services sessions. The first user to log on uses session 0, the next user to log on uses session 1, and so on. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can support multiple users.

 

For Windows 2000:  If Terminal Services is not running, the "Global\" and "Local\" prefixes are ignored. The remainder of the name can contain any character except the backslash character.

 

For Windows NT 4.0 and earlier:  The name can contain any character except the backslash character.

 

For Windows Me/98/95:  The name can contain any character except the backslash character. The empty string ("") is a valid object name.