您的位置:首页 > 其它

事件对象相关函数与例子(MSDN)

2007-03-21 10:59 260 查看
北京智盟IT培训中心推出超高性价比的C++课程,小班授课、学费1000元,由名师主讲,咨询电话:010-52850976。

事件对象相关函数与例子(MSDN)

CreateEvent
The CreateEvent function creates or opens a named or unnamed event object.

HANDLE CreateEvent(
LPSECURITY_ATTRIBUTES lpEventAttributes, // SD
BOOL bManualReset, // reset type
BOOL bInitialState, // initial state
LPCTSTR lpName // object name
);
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.
Windows NT/2000/XP: 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.

bManualReset
[in] Specifies whether a manual-reset or auto-reset event object is created. If TRUE, then you must use the ResetEvent function to manually reset the state to nonsignaled. If FALSE, the system automatically resets the state to nonsignaled after a single waiting thread has been released.
bInitialState
[in] Specifies the initial state of the event object. If TRUE, the initial state is signaled; otherwise, it is nonsignaled.
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 EVENT_ALL_ACCESS access to the existing object. 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 more information, see Kernel Object Name Spaces.

Windows XP: 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.

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.

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

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

Return Values
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.

Remarks
The handle returned by CreateEvent has EVENT_ALL_ACCESS access to the new event object and can be used in any function that requires a handle to an event object.

Any thread of the calling process can specify the event-object handle in a call to one of the wait functions. The single-object wait functions return when the state of the specified object is signaled. The multiple-object wait functions can be instructed to return either when any one or when all of the specified objects are signaled. When a wait function returns, the waiting thread is released to continue its execution.

The initial state of the event object is specified by the bInitialState parameter. Use the SetEvent function to set the state of an event object to signaled. Use the ResetEvent function to reset the state of an event object to nonsignaled.

When the state of a manual-reset event object is signaled, it remains signaled until it is explicitly reset to nonsignaled by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait operations for the specified event object, can be released while the object's state is signaled.

When the state of an auto-reset event object is signaled, it remains signaled until a single waiting thread is released; the system then automatically resets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled.

Multiple processes can have handles of the same event object, enabling use of the object for interprocess synchronization. The following object-sharing mechanisms are available:

A child process created by the CreateProcess function can inherit a handle to an event object if the lpEventAttributes parameter of CreateEvent enabled inheritance.
A process can specify the event-object handle in a call to the DuplicateHandle function to create a duplicate handle that can be used by another process.
A process can specify the name of an event object in a call to the OpenEvent or CreateEvent function.
Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The event object is destroyed when its last handle has been closed.

Windows 95/98/Me: CreateEventW 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.

Example Code
For an example that uses CreateEvent, see Using Event Objects.

Requirements
Windows NT/2000/XP: Included in Windows NT 3.1 and later.
Windows 95/98/Me: Included in Windows 95 and later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000/XP. Also supported by Microsoft Layer for Unicode.

See Also
Synchronization Overview, Synchronization Functions, CloseHandle, CreateProcess, DuplicateHandle, OpenEvent, ResetEvent, SECURITY_ATTRIBUTES, SetEvent, Object Names

SetEvent
The SetEvent function sets the specified event object to the signaled state.

BOOL SetEvent(
HANDLE hEvent // handle to event
);
Parameters
hEvent
[in] Handle to the event object. The CreateEvent or OpenEvent function returns this handle.
Windows NT/2000/XP: The handle must have EVENT_MODIFY_STATE access. For more information, see Synchronization Object Security and Access Rights.

Return Values
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.

Remarks
The state of a manual-reset event object remains signaled until it is set explicitly to the nonsignaled state by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait operations for the specified event object by calling one of the wait functions, can be released while the object's state is signaled.

The state of an auto-reset event object remains signaled until a single waiting thread is released, at which time the system automatically sets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled.

Example Code
For an example that uses SetEvent, see Using Event Objects.

Requirements
Windows NT/2000/XP: Included in Windows NT 3.1 and later.
Windows 95/98/Me: Included in Windows 95 and later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also
Synchronization Overview, Synchronization Functions, CreateEvent, OpenEvent, PulseEvent, ResetEvent

OpenEvent
The OpenEvent function opens an existing named event object.

HANDLE OpenEvent(
DWORD dwDesiredAccess, // access
BOOL bInheritHandle, // inheritance option
LPCTSTR lpName // object name
);
Parameters
dwDesiredAccess
[in] Specifies the requested access to the event object. For systems that support object security, the function fails if the security descriptor of the specified object does not permit the requested access for the calling process.
This parameter can be any combination of the following values. Access Description
EVENT_ALL_ACCESS Specifies all possible access flags for the event object.
EVENT_MODIFY_STATE Enables use of the event handle in the SetEvent and ResetEvent functions to modify the event's state.
SYNCHRONIZE Windows NT/2000/XP: Enables use of the event handle in any of the wait functions to wait for the event's state to be signaled.

bInheritHandle
[in] Specifies whether the returned handle is inheritable. If TRUE, a process created by the CreateProcess function can inherit the handle; otherwise, the handle cannot be inherited.
lpName
[in] Pointer to a null-terminated string that names the event to be opened. Name comparisons are case sensitive.
Terminal Services: The name can have a "Global/" or "Local/" prefix to explicitly open an object in the global or session name space. The remainder of the name can contain any character except the backslash character (/). For more information, see Kernel Object Name Spaces.

Windows XP: 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.

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.

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

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

Return Values
If the function succeeds, the return value is a handle to the event object.

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

Remarks
The OpenEvent function enables multiple processes to open handles of the same event object. The function succeeds only if some process has already created the event by using the CreateEvent function. The calling process can use the returned handle in any function that requires a handle to an event object, subject to the limitations of the access specified in the dwDesiredAccess parameter.

The handle can be duplicated by using the DuplicateHandle function. Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The event object is destroyed when its last handle has been closed.

Windows 95/98/Me: OpenEventW 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.

Requirements
Windows NT/2000/XP: Included in Windows NT 3.1 and later.
Windows 95/98/Me: Included in Windows 95 and later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000/XP. Also supported by Microsoft Layer for Unicode.

See Also
Synchronization Overview, Synchronization Functions, CloseHandle, CreateEvent, CreateProcess, DuplicateHandle, PulseEvent, ResetEvent, SetEvent, Object Names

ResetEvent
The ResetEvent function sets the specified event object to the nonsignaled state.

BOOL ResetEvent(
HANDLE hEvent // handle to event
);
Parameters
hEvent
[in] Handle to the event object. The CreateEvent or OpenEvent function returns this handle.
Windows NT/2000/XP: The handle must have EVENT_MODIFY_STATE access. For more information, see Synchronization Object Security and Access Rights.

Return Values
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.

Remarks
The state of an event object remains nonsignaled until it is explicitly set to signaled by the SetEvent or PulseEvent function. This nonsignaled state blocks the execution of any threads that have specified the event object in a call to one of the wait functions.

The ResetEvent function is used primarily for manual-reset event objects, which must be set explicitly to the nonsignaled state. Auto-reset event objects automatically change from signaled to nonsignaled after a single waiting thread is released.

Example Code
For an example that uses ResetEvent, see Using Event Objects.

Requirements
Windows NT/2000/XP: Included in Windows NT 3.1 and later.
Windows 95/98/Me: Included in Windows 95 and later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also
Synchronization Overview, Synchronization Functions, CreateEvent, OpenEvent, PulseEvent, SetEvent

Using Event Objects
Applications use event objects in a number of situations to notify a waiting thread of the occurrence of an event. For example, overlapped I/O operations on files, named pipes, and communications devices use an event object to signal their completion. For more information about the use of event objects in overlapped I/O operations, see Synchronization and Overlapped Input and Output.

In the following example, an application uses event objects to prevent several threads from reading from a shared memory buffer while a master thread is writing to that buffer. First, the master thread uses the CreateEvent function to create a manual-reset event object. The master thread sets the event object to nonsignaled when it is writing to the buffer and then resets the object to signaled when it has finished writing. Then it creates several reader threads and an auto-reset event object for each thread. Each reader thread sets its event object to signaled when it is not reading from the buffer.

#define NUMTHREADS 4

HANDLE hGlobalWriteEvent;

void CreateEventsAndThreads(void)
{
HANDLE hReadEvents[NUMTHREADS], hThread;
DWORD i, IDThread;

// Create a manual-reset event object. The master thread sets
// this to nonsignaled when it writes to the shared buffer.

hGlobalWriteEvent = CreateEvent(
NULL, // no security attributes
TRUE, // manual-reset event
TRUE, // initial state is signaled
"WriteEvent" // object name
);

if (hGlobalWriteEvent == NULL) {
// error exit
}

// Create multiple threads and an auto-reset event object
// for each thread. Each thread sets its event object to
// signaled when it is not reading from the shared buffer.

for(i = 1; i <= NUMTHREADS; i++)
{
// Create the auto-reset event.
hReadEvents[i] = CreateEvent(
NULL, // no security attributes
FALSE, // auto-reset event
TRUE, // initial state is signaled
NULL); // object not named

if (hReadEvents[i] == NULL)
{
// Error exit.
}

hThread = CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE) ThreadFunction,
&hReadEvents[i], // pass event handle
0, &IDThread);
if (hThread == NULL)
{
// Error exit.
}
}
}
Before the master thread writes to the shared buffer, it uses the ResetEvent function to set the state of hGlobalWriteEvent (an application-defined global variable) to nonsignaled. This blocks the reader threads from starting a read operation. The master then uses the WaitForMultipleObjects function to wait for all reader threads to finish any current read operations. When WaitForMultipleObjects returns, the master thread can safely write to the buffer. After it has finished, it sets hGlobalWriteEvent and all the reader-thread events to signaled, enabling the reader threads to resume their read operations.

VOID WriteToBuffer(VOID)
{
DWORD dwWaitResult, i;

// Reset hGlobalWriteEvent to nonsignaled, to block readers.

if (! ResetEvent(hGlobalWriteEvent) )
{
// Error exit.
}

// Wait for all reading threads to finish reading.

dwWaitResult = WaitForMultipleObjects(
NUMTHREADS, // number of handles in array
hReadEvents, // array of read-event handles
TRUE, // wait until all are signaled
INFINITE); // indefinite wait

switch (dwWaitResult)
{
// All read-event objects were signaled.
case WAIT_OBJECT_0:
// Write to the shared buffer.
break;

// An error occurred.
default:
printf("Wait error: %d ", GetLastError());
ExitProcess(0);
}

// Set hGlobalWriteEvent to signaled.

if (! SetEvent(hGlobalWriteEvent) )
{
// Error exit.
}

// Set all read events to signaled.
for(i = 1; i <= NUMTHREADS; i++)
if (! SetEvent(hReadEvents[i]) ) {
// Error exit.
}
}
Before starting a read operation, each reader thread uses WaitForMultipleObjects to wait for the application-defined global variable hGlobalWriteEvent and its own read event to be signaled. When WaitForMultipleObjects returns, the reader thread's auto-reset event has been reset to nonsignaled. This blocks the master thread from writing to the buffer until the reader thread uses the SetEvent function to set the event's state back to signaled.

VOID ThreadFunction(LPVOID lpParam)
{
DWORD dwWaitResult;
HANDLE hEvents[2];

hEvents[0] = *(HANDLE*)lpParam; // thread's read event
hEvents[1] = hGlobalWriteEvent;

dwWaitResult = WaitForMultipleObjects(
2, // number of handles in array
hEvents, // array of event handles
TRUE, // wait till all are signaled
INFINITE); // indefinite wait

switch (dwWaitResult)
{

// Both event objects were signaled.
case WAIT_OBJECT_0:
// Read from the shared buffer.
break;

// An error occurred.
default:
printf("Wait error: %d ", GetLastError());
ExitThread(0);
}

// Set the read event to signaled.

if (! SetEvent(hEvents[0]) )
{
// Error exit.
}
}




输入您的搜索字词
提交搜索表单
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: