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


 

 

The Windows Process, thread and synchronization: Functions, structures and other related items used in program examples of Windows Process, Thread & Synchronization 1, Windows Process, Thread & Synchronization 2, Windows Process, Thread & Synchronization 3, Windows Process, Thread & Synchronization 4, Windows Process, Thread & Synchronization 5 and Windows Process, Thread & Synchronization 6, wherever applicable. To learn about function you can jump to C & C++ function tutorials.

 

Index:

  1. WriteFile()

  2. FindFirstChangeNotification()

  3. FindNextChangeNotification()

  4. FindCloseChangeNotification()

  5. CreateTimerQueueTimer()

  6. WaitOrTimerCallback()

  7. InitializeSListHead()

  8. InterlockedPushEntrySList()

  9. InterlockedPopEntrySList()

  10. InterlockedFlushSList()

  11. SetWaitableTimer()

  12. CreateWaitableTimer()

  13. DeleteTimerQueue()

  14. DeleteTimerQueueEx()

  15. CreateTimerQueue()

  16. ThreadProc()

  17. PeekMessage()

  18. DispatchMessage()

  19. WaitForInputIdle()

  20. MsgWaitForMultipleObjects()

 

 

WriteFile()

 

Item

Description

Function

WriteFile().

Use

Writes data to a file at the position specified by the file pointer. This function is designed for both synchronous and asynchronous operation.  The WriteFileEx() function is designed solely for asynchronous operation.

Prototype

BOOL WriteFile( HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite,

  LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped);

Parameters

See below.

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().

Include file

<windows.h>

Remark

See below.

 

Table 1.

 

 

 

 

Parameters

 

hFile - [in] Handle to the file. The file handle must have been created with the GENERIC_WRITE access right.

For asynchronous write operations, hFile can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile() function, or a socket handle returned by the socket or accept function.

Windows Me/98/95:  For asynchronous write operations, hFile can be a communications resource opened with the FILE_FLAG_OVERLAPPED flag by CreateFile(), or a socket handle returned by socket or accept. You cannot perform asynchronous write operations on mailslots, named pipes, or disk files.

lpBuffer - [in] Pointer to the buffer containing the data to be written to the file.

nNumberOfBytesToWrite - [in] Number of bytes to be written to the file.

A value of zero specifies a null write operation. The behavior of a null write operation depends on the underlying file system. To truncate or extend a file, use the SetEndOfFile() function. Named pipe write operations across a network are limited to 65,535 bytes.

lpNumberOfBytesWritten - [out] Pointer to the variable that receives the number of bytes written. WriteFile() sets this value to zero before doing any work or error checking. If lpOverlapped is NULL, lpNumberOfBytesWritten cannot be NULL. If lpOverlapped is not NULL, lpNumberOfBytesWritten can be NULL. If this is an overlapped write operation, you can get the number of bytes written by calling GetOverlappedResult(). If hFile is associated with an I/O completion port, you can get the number of bytes written by calling GetQueuedCompletionStatus().

If I/O completion ports are used and you are using a callback routine to free the memory allocated to the OVERLAPPED structure pointed to by the lpOverlapped parameter, specify NULL as the value of this parameter to avoid a memory corruption problem during the de-allocation. This memory corruption problem will cause an invalid number of bytes to be returned in this parameter. For Windows Me/98/95:  This parameter cannot be NULL.

lpOverlapped - [in] Pointer to an OVERLAPPED structure. This structure is required if hFile was opened with FILE_FLAG_OVERLAPPED.

If hFile was opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must not be NULL. It must point to a valid OVERLAPPED structure. If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the function can incorrectly report that the write operation is complete.

If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the write operation starts at the offset specified in the OVERLAPPED structure and WriteFile() may return before the write operation has been completed. In this case, WriteFile() returns FALSE and the GetLastError() function returns ERROR_IO_PENDING. This allows the calling process to continue processing while the write operation is being completed. The event specified in the OVERLAPPED structure is set to the signaled state upon completion of the write operation. The caller must adjust the position of the file pointer upon completion.

If hFile was not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the write operation starts at the current file position and WriteFile() does not return until the operation has been completed. The system updates the file pointer upon completion.

WriteFile() resets the event specified by the hEvent member of the OVERLAPPED structure to a non-signaled state when it begins the I/O operation. Therefore, there is no need for the caller to do so. If hFile was not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the write operation starts at the offset specified in the OVERLAPPED structure and WriteFile() does not return until the write operation has been completed. The system updates the file pointer upon completion. Windows Me/98/95:  For operations on files, disks, pipes, or mailslots, this parameter must be NULL; a pointer to an OVERLAPPED structure causes the call to fail. However, the function supports overlapped I/O on serial and parallel ports.

 

Remarks

 

The WriteFile() function may fail with ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY whenever there are too many outstanding asynchronous I/O requests. To cancel all pending asynchronous I/O operations, use the CancelIo() function. This function only cancels operations issued by the calling thread for the specified file handle. I/O operations that are canceled complete with the error ERROR_OPERATION_ABORTED. When writing to a file, the last write time is not fully updated until all handles used for writing have been closed. Therefore, to ensure an accurate last write time, close the file handle immediately after writing to the file.

If part of the file is locked by another process and the write operation overlaps the locked portion, WriteFile() fails.  Accessing the output buffer while a write operation is using the buffer may lead to corruption of the data written from that buffer. Applications must not write to, reallocate, or free the output buffer that a write operation is using until the write operation completes.  An application must meet certain requirements when working with files opened with FILE_FLAG_NO_BUFFERING:

  1. File access must begin at byte offsets within the file that are integer multiples of the volume's sector size. To determine a volume's sector size, call the GetDiskFreeSpace() function.

  2. File access must be for numbers of bytes that are integer multiples of the volume's sector size. For example, if the sector size is 512 bytes, an application can request reads and writes of 512, 1024, or 2048 bytes, but not of 335, 981, or 7171 bytes.

  3. Buffer addresses for read and write operations must be sector aligned (aligned on addresses in memory that are integer multiples of the volume's sector size). One way to sector align buffers is to use the VirtualAlloc() function to allocate the buffers. This function allocates memory that is aligned on addresses that are integer multiples of the system's page size. Because both page and volume sector sizes are powers of 2, memory aligned by multiples of the system's page size is also aligned by multiples of the volume's sector size.

 

Note that the time stamps may not be updated correctly for a remote file. To ensure consistent results, use unbuffered I/O.  The system interprets zero bytes to write as specifying a null write operation and WriteFile() does not truncate or extend the file. To truncate or extend a file, use the SetEndOfFile() function. When writing to a non-blocking, byte-mode pipe handle with insufficient buffer space, WriteFile() returns TRUE with:

*lpNumberOfBytesWritten < nNumberOfBytesToWrite

When an application uses the WriteFile() function to write to a pipe, the write operation may not finish if the pipe buffer is full. The write operation is completed when a read operation (using the ReadFile() function) makes more buffer space available.

If the anonymous read pipe handle has been closed and WriteFile() attempts to write using the corresponding anonymous write pipe handle, the function returns FALSE and GetLastError() returns ERROR_BROKEN_PIPE. Characters can be written to the screen buffer using WriteFile() with a handle to console output. The exact behavior of the function is determined by the console mode. The data is written to the current cursor position. The cursor position is updated after the write operation.

If you are attempting to write to a floppy drive that does not have a floppy disk, the system displays a message box prompting the user to retry the operation. To prevent the system from displaying this message box, call the SetErrorMode() function with SEM_NOOPENFILEERRORBOX.

 

FindFirstChangeNotification()

 

Item

Description

Function

FindFirstChangeNotification().

Use

To create a change notification handle and sets up initial change notification filter conditions. A wait on a notification handle succeeds when a change matching the filter conditions occurs in the specified directory or subtree. However, the function does not indicate the change that satisfied the wait condition.  To retrieve information about the specific change as part of the notification, use the ReadDirectoryChangesW() function.

Prototype

HANDLE FindFirstChangeNotification( LPCTSTR lpPathName, BOOL bWatchSubtree, DWORD dwNotifyFilter);

Parameters

See below.

Return value

If the function succeeds, the return value is a handle to a find change notification object.  If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError().  If the network redirector or the target file system does not support this operation, the function fails with ERROR_INVALID_FUNCTION.

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.  The wait functions can monitor the specified directory or subtree by using the handle returned by the FindFirstChangeNotification() function. A wait is satisfied when one of the filter conditions occurs in the monitored directory or subtree.  After the wait has been satisfied, the application can respond to this condition and continue monitoring the directory by calling the FindNextChangeNotification() function and the appropriate wait function. When the handle is no longer needed, it can be closed by using the FindCloseChangeNotification() function.

Windows Me/98/95:  FindFirstChangeNotificationW() is supported by the Microsoft Layer for Unicode. To use this, you must add certain files to your application, as outlined in Microsoft Layer for Unicode on Windows 95/98/Me Systems.

 

Table 2.

 

Parameters

 

lpPathName - [in] Pointer to a null-terminated string that specifies the path of the directory to watch.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.  For Windows Me/98/95:  This string must not exceed MAX_PATH characters.

bWatchSubtree - [in] Specifies whether the function will monitor the directory or the directory tree. If this parameter is TRUE, the function monitors the directory tree rooted at the specified directory; if it is FALSE, it monitors only the specified directory.

dwNotifyFilter - [in] Filter conditions that satisfy a change notification wait. This parameter can be one or more of the following values.

 

Value

Meaning

FILE_NOTIFY_CHANGE_FILE_NAME

Any file name change in the watched directory or subtree causes a change notification wait operation to return. Changes include renaming, creating, or deleting a file name.

FILE_NOTIFY_CHANGE_DIR_NAME

Any directory-name change in the watched directory or subtree causes a change notification wait operation to return. Changes include creating or deleting a directory.

FILE_NOTIFY_CHANGE_ATTRIBUTES

Any attribute change in the watched directory or subtree causes a change notification wait operation to return.

FILE_NOTIFY_CHANGE_SIZE

Any file-size change in the watched directory or subtree causes a change notification wait operation to return. The operating system detects a change in file size only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.

FILE_NOTIFY_CHANGE_LAST_WRITE

Any change to the last write-time of files in the watched directory or subtree causes a change notification wait operation to return. The operating system detects a change to the last write-time only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.

FILE_NOTIFY_CHANGE_SECURITY

Any security-descriptor change in the watched directory or subtree causes a change notification wait operation to return.

 

Table 3

 

FindNextChangeNotification()

 

Item

Description

Function

FindNextChangeNotification().

Use

To request that the operating system signal a change notification handle the next time it detects an appropriate change.

Prototype

BOOL FindNextChangeNotification(HANDLE hChangeHandle);

Parameters

hChangeHandle - [in] Handle to a change notification handle created by the FindFirstChangeNotification() function.

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().

Include file

<windows.h>

Remark

After the FindNextChangeNotification() function returns successfully, the application can wait for notification that a change has occurred by using the wait functions.  If a change occurs after a call to FindFirstChangeNotification() but before a call to FindNextChangeNotification(), the operating system records the change. When FindNextChangeNotification() is executed, the recorded change immediately satisfies a wait for the change notification.  FindNextChangeNotification() should not be used more than once on the same handle without using one of the wait functions. An application may miss a change notification if it uses FindNextChangeNotification() when there is a change request outstanding.  When hChangeHandle is no longer needed, close it by using the FindCloseChangeNotification() function.

 

Table 4.

 

FindCloseChangeNotification()

 

Item

Description

Function

FindCloseChangeNotification().

Use

To stop change notification handle monitoring.

Prototype

BOOL FindCloseChangeNotification(HANDLE hChangeHandle);

Parameters

hChangeHandle - [in] Handle to a change notification handle created by the FindFirstChangeNotification() function.

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().

Include file

<windows.h>

Remark

After the FindCloseChangeNotification() function is called, the handle specified by the hChangeHandle parameter cannot be used in subsequent calls to either the FindNextChangeNotification() or FindCloseChangeNotification() function.  Change notifications can also be used in the wait functions.

 

Table 5.

 

CreateTimerQueueTimer()

 

Item

Description

Function

CreateTimerQueueTimer().

Use

Creates a timer-queue timer. This timer expires at the specified due time, then after every specified period. When the timer expires, the callback() function is called.

Prototype

BOOL CreateTimerQueueTimer( PHANDLE phNewTimer, HANDLE TimerQueue, WAITORTIMERCALLBACK Callback, PVOID Parameter, DWORD DueTime, DWORD Period, ULONG Flags);

Parameters

See below.

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().

Include file

<windows.h>

Remark

See below.

 

Table 6.

 

Parameter

 

phNewTimer - [out] Pointer to a buffer that receives a handle to the timer-queue timer on return. When this handle has expired and is no longer required, release it by calling DeleteTimerQueueTimer().

TimerQueue - [in] Handle to a timer queue. This handle is returned by the CreateTimerQueue() function. If this parameter is NULL, the timer is associated with the default timer queue.

Callback - [in] Pointer to the application-defined function of type WAITORTIMERCALLBACK to be executed when the timer expires.

Parameter - [in] Single parameter value that will be passed to the callback function.

DueTime - [in] Amount of time to elapse before the timer is to be set to the signaled state for the first time, in milliseconds.

Period - [in] Period of the timer, in milliseconds. If this parameter is zero, the timer is signaled once. If this parameter is greater than zero, the timer is periodic. A periodic timer automatically reactivates each time the period elapses, until the timer is canceled.

Flags - [in] This parameter can be one or more of the following values.

 

Value

Meaning

WT_EXECUTEINTIMERTHREAD

The callback() function is invoked by the timer thread itself. This flag should be used only for short tasks or it could affect other timer operations.  The callback function is queued as an APC. It should not perform alertable wait operations.

WT_EXECUTEINIOTHREAD

The callback() function is queued to an I/O worker thread. This flag should be used if the function should be executed in a thread that waits in an alertable state. The callback function is queued as an APC. Be sure to address reentrancy issues if the function performs an alertable wait operation.

WT_EXECUTEINPERSISTENTTHREAD

The callback() function is queued to a thread that never terminates. It does not guarantee that the same thread is used each time. This flag should be used only for short tasks or it could affect other timer operations.  Note that currently no worker thread is truly persistent, although no worker thread will terminate if there are any pending I/O requests.

WT_EXECUTELONGFUNCTION

The callback function can perform a long wait. This flag helps the system to decide if it should create a new thread.

WT_EXECUTEONLYONCE

The timer will be set to the signaled state only once.

WT_TRANSFER_IMPERSONATION

Callback() functions will use the current access token, whether it is a process or impersonation token. If this flag is not specified, callback functions execute only with the process token.  Windows XP and Windows 2000:  This flag is not supported until Windows XP SP2 and Windows Server 2003.

 

Table 7

 

Remarks

 

If the DueTime and Period parameters are both nonzero, the timer will be signaled first at the due time, then periodically. The callback() is called every time the period elapses, whether or not the previous callback has finished executing. Callback() functions are queued to the thread pool. These threads are subject to scheduling delays, so the timing can vary depending on what else is happening in the application or the system. To cancel a timer, call the DeleteTimerQueueTimer() function. To cancel all timers in a timer queue, call the DeleteTimerQueueEx() function. By default, the thread pool has a maximum of 500 threads. To raise this limit, use the WT_SET_MAX_THREADPOOL_THREAD macro defined in winnt.h.

#define WT_SET_MAX_THREADPOOL_THREADS(Flags,Limit) ((Flags)|=(Limit)<<16)

Use this macro when specifying the Flags parameter. The macro parameters are the desired flags and the new limit (up to (2<<16)-1 threads). However, note that your application can improve its performance by keeping the number of worker threads low.  To compile an application that uses this function, define the _WIN32_WINNT macro as 0x0500 or later.

 

WaitOrTimerCallback()

 

Item

Description

Function

WaitOrTimerCallback().

Use

Is an application-defined function that serves as the starting address for a timer callback or a registered wait callback. Specify this address when calling the CreateTimerQueueTimer(), RegisterWaitForSingleObject() function.  The WAITORTIMERCALLBACK type defines a pointer to this callback() function. WaitOrTimerCallback() is a placeholder for the application-defined function name.

Prototype

VOID CALLBACK WaitOrTimerCallback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);

Parameters

lpParameter - Receives the thread data passed to the function using a parameter of the CreateTimerQueueTimer() or RegisterWaitForSingleObject() function.

TimerOrWaitFired - If this parameter is TRUE, the wait timed out. If this parameter is FALSE, the wait event has been signaled. This parameter is always TRUE for timer callbacks.

Return value

This function does not return a value.

Include file

<windows.h>

Remark

This callback function must not call the TerminateThread() function.

 

Table 8.

 

InitializeSListHead()

 

Item

Description

Function

InitializeSListHead()

Use

Initializes the head of a singly linked list.

Prototype

void InitializeSListHead(PSLIST_HEADER ListHead);

Parameters

ListHead - Pointer to an SLIST_HEADER structure that represents the head of a singly linked list. This structure is for system use only.

Return value

This function does not return a value.

Include file

<windows.h>

Remark

All list items must be aligned on a heap allocation boundary. Unaligned items can cause unpredictable results.  To add items to the list, use the InterlockedPushEntrySList() function. To remove items from the list, use the InterlockedPopEntrySList() function.

 

Table 9.

 

InterlockedPushEntrySList()

 

Item

Description

Function

InterlockedPushEntrySList().

Use

Inserts an item at the front of a singly linked list. Access to the list is synchronized on a multiprocessor system.

Prototype

PSLIST_ENTRY InterlockedPushEntrySList( PSLIST_HEADER ListHead, PSLIST_ENTRY ListEntry);

Parameters

ListHead - Pointer to an SLIST_HEADER structure that represents the head of a singly linked list. This structure is for system use only.

ListEntry - Pointer to an SLIST_ENTRY structure that represents an item in a singly linked list.

Return value

The return value is the previous first item in the list. If the list was previously empty, the return value is NULL.

Include file

<windows.h>

Remark

All list items must be aligned on a heap allocation boundary. Unaligned items can cause unpredictable results.

 

Table 10.

 

InterlockedPopEntrySList()

 

Item

Description

Function

InterlockedPopEntrySList().

Use

Removes an item from the front of a singly linked list. Access to the list is synchronized on a multiprocessor system.

Prototype

PSLIST_ENTRY InterlockedPopEntrySList( PSLIST_HEADER ListHead);

Parameters

ListHead - Pointer to an SLIST_HEADER structure that represents the head of a singly linked list. This structure is for system use only.

Return value

The return value is a pointer to the item removed from the list. If the list is empty, the return value is NULL.

Include file

<windows.h>

Remark

All list items must be aligned on a heap allocation boundary. Unaligned items can cause unpredictable results.

 

Table 11.

 

InterlockedFlushSList()

 

Item

Description

Function

InterlockedFlushSList().

Use

Removes all items from a singly linked list. Access to the list is synchronized on a multiprocessor system.

Prototype

PSLIST_ENTRY InterlockedFlushSList(PSLIST_HEADER ListHead);

Parameters

ListHead - Pointer to an SLIST_HEADER structure that represents the head of the singly linked list. This structure is for system use only.

Return value

The return value is a pointer to the items removed from the list. If the list is empty, the return value is NULL.

Include file

<windows.h>

Remark

All list items must be aligned on a heap allocation boundary. Unaligned items can cause unpredictable results.

 

Table 12.

 

SetWaitableTimer()

 

Item

Description

Function

SetWaitableTimer().

Use

Activates the specified waitable timer. When the due time arrives, the timer is signaled and the thread that set the timer calls the optional completion routine.

Prototype

BOOL SetWaitableTimer( HANDLE hTimer, const LARGE_INTEGER* pDueTime, LONG lPeriod, PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, BOOL fResume );

Parameters

See below.

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().

Include file

<windows.h>

Remark

Timers are initially inactive. To activate a timer, call SetWaitableTimer(). If the timer is already active when you call SetWaitableTimer(), the timer is stopped, then it is reactivated. Stopping the timer in this manner does not set the timer state to signaled, so threads blocked in a wait operation on the timer remain blocked.

When the specified due time arrives, the timer becomes inactive and the APC is queued to the thread that set the timer. The state of the timer is set to signaled, the timer is reactivated using the specified period, and the thread that set the timer calls the completion routine when it e