Message-ID: <4BPiK5$wfm@bbs.sdu.edu.cn>
Subject: Per-handle Data and Per-I/O Operation Data
Date: Sun, 28 Mar 2004 12:06:29 +0000
From: onek.bbs@bbs.sdu.edu.cn (�式�)
Path: news.cnusenet.org!archive.usenet.blueworldhosting.com!illumos!news.pugleaf.net!.TX!i2pn2.pugleaf.net!archive.newsdeef.eu!mbox2nntp-cn.bbs.comp.lang.mbox.zip!archiver1.google.com!news1.google.com!news.glorb.com!news.moat.net!ctu-peer!news.nctu.edu.tw!netnews.csie.nctu.edu.tw!maily.cic.tsinghua.edu.cn!netnews.sdu.edu.cn!SDU
Newsgroups: cn.bbs.comp.lang
Organization: 泉������
X-Filename: Programming/M.1080475589.A
Xref: news.cnusenet.org cn.bbs.comp.lang:18077


When a worker thread receives I/O completion notification from the GetQueuedCo
mpletionStatus API call, the lpCompletionKey and lpOverlapped parameters conta
in socket information that can be used to continue processing I/O on a socket 
through the completion port. Two types of important socket data are available 
through these parameters: per-handle data and per-I/O operation data.

The lpCompletionKey parameter contains what we call per-handle data because th
e data is related to a socket handle when a socket is first associated with th
e completion port. This is the data that is passed as the CompletionKey parame
ter of the CreateIoCompletionPort API call. As we noted earlier, your applicat
ion can pass any type of socket information through this parameter. Typically,
 applications will store the socket handle related to the I/O request here.

The lpOverlapped parameter contains an OVERLAPPED structure followed by what w
e call per-I/O operation data, which is anything that your worker thread will 
need to know when processing a completion packet (echo the data back, accept t
he connection, post another read, and so on). Per-I/O operation data is any nu
mber of bytes contained in a structure also containing an OVERLAPPED structure
 that you pass into a function that expects an OVERLAPPED structure. A simple 
way to make this work is to define a structure and place an OVERLAPPED structu
re as a field of the new structure. For example, we declare the following data
 structure to manage per-I/O operation data:

typedef struct
{
    OVERLAPPED Overlapped;
    char       Buffer[DATA_BUFSIZE];
    int			   BufferLen;
    int        OperationType;
} PER_IO_DATA;
This structure demonstrates some important data elements you might want to rel
ate to an I/O operation, such as the type of I/O operation (a send or receive 
request) that just completed. In this structure, we consider the data buffer f
or the completed I/O operation to be useful. To call a Winsock API function th
at expects an OVERLAPPED structure, you dereference the OVERLAPPED element of 
your structure. For example,

PER_IO_OPERATION_DATA PerIoData;
WSABUF wbuf;
DWORD Bytes, Flags;
// Initialize wbuf ...
WSARecv(socket, &wbuf, 1, &Bytes, &Flags, &(PerIoData.Overlapped), 
NULL);
Later in the worker thread, GetQueuedCompletionStatus returns with an overlapp
ed structure and completion key. To retrieve the per-I/O data the macro CONTAI
NING_RECORD should be used. For example,

PER_IO_DATA  *PerIoData=NULL;
OVERLAPPED   *lpOverlapped=NULL;

ret = GetQueuedCompletionStatus(
         CompPortHandle,
         &Transferred,
         (PULONG_PTR)&CompletionKey,
         &lpOverlapped,
			INFINITE);
// Check for successful return
PerIoData = CONTAINING_RECORD(lpOverlapped, PER_IO_DATA, Overlapped);
This macro should be used; otherwise, the OVERLAPPED member of the PER_IO_DATA
 structure would always have to appear first, which can be a dangerous assumpt
ion to make (especially with multiple developers working on the same code).

You can determine which operation was posted on this handle by using a field o
f the per-I/O structure to indicate the type of operation posted. In our examp
le, the OperationType member would be set to indicate a read, write, etc., ope
ration. One of the biggest benefits of per-I/O operation data is that it allow
s you to manage multiple I/O operations (such as read/write, multiple reads, a
nd multiple writes) on the same handle. You might ask why you would want to po
st more than one I/O operation at a time on a socket. The answer is scalabilit
y. For example, if you have a multiple-processor machine with a worker thread 
using each processor, you could potentially have several processors sending an
d receiving data on a socket at the same time.

Before continuing, there is one other important aspect about Windows completio
n ports that needs to be stressed. All overlapped operations are guaranteed to
 be executed in the order that the application issued them. However, the compl
etion notifications returned from a completion port are not guaranteed to be i
n that same order. That is, if an application posts two overlapped WSARecv ope
rations, one with a 10 KB buffer and the next with a 12 KB buffer, the 10 KB b
uffer is filled first, followed by the 12 KB buffer. The application's worker 
thread may receive notification from GetQueuedCompletionStatus for the 12 KB W
SARecv before the completion event for the 10 KB operation. Of course, this is
 only an issue when multiple operations are posted on a socket.

To complete this simple echo server sample, we need to supply a ServerWorkerTh
read function. The following code outlines how to develop a worker thread rout
ine that uses per-handle data and per-I/O operation data to service I/O reques
ts.

 DWORD WINAPI ServerWorkerThread(
    LPVOID CompletionPortID)
{
    HANDLE CompletionPort = (HANDLE) CompletionPortID;
    DWORD BytesTransferred;
    LPOVERLAPPED Overlapped;
    LPPER_HANDLE_DATA PerHandleData;
    LPPER_IO_DATA PerIoData;
    DWORD SendBytes, RecvBytes;
    DWORD Flags;
    
    while(TRUE)
    {
        // Wait for I/O to complete on any socket
        // associated with the completion port
    
        ret = GetQueuedCompletionStatus(CompletionPort,
            &BytesTransferred,(LPDWORD)&PerHandleData,
            (LPOVERLAPPED *) &PerIoData, INFINITE);

        // First check to see if an error has occurred
        // on the socket; if so, close the 
        // socket and clean up the per-handle data
        // and per-I/O operation data associated with
        // the socket

        if (BytesTransferred == 0 &&
            (PerIoData->OperationType == RECV_POSTED ����
             PerIoData->OperationType == SEND_POSTED))
        {
            // A zero BytesTransferred indicates that the
            // socket has been closed by the peer, so
            // you should close the socket. Note: 
            // Per-handle data was used to reference the
            // socket associated with the I/O operation.
 
            closesocket(PerHandleData->Socket);

            GlobalFree(PerHandleData);
            GlobalFree(PerIoData);
            continue;
        }

        // Service the completed I/O request. You can
        // determine which I/O request has just
        // completed by looking at the OperationType
        // field contained in the per-I/O operation data.
         if (PerIoData->OperationType == RECV_POSTED)
        {
            // Do something with the received data
            // in PerIoData->Buffer
        }

        // Post another WSASend or WSARecv operation.
        // As an example, we will post another WSARecv()
        // I/O operation.

        Flags = 0;

        // Set up the per-I/O operation data for the next
        // overlapped call
        ZeroMemory(&(PerIoData->Overlapped),
            sizeof(OVERLAPPED));

        PerIoData->DataBuf.len = DATA_BUFSIZE;
        PerIoData->DataBuf.buf = PerIoData->Buffer;
        PerIoData->OperationType = RECV_POSTED;

        WSARecv(PerHandleData->Socket, 
            &(PerIoData->DataBuf), 1, &RecvBytes,
            &Flags, &(PerIoData->Overlapped), NULL);
    }
}
If an error has occurred for a given overlapped operation, GetQueuedCompletion
Status will return FALSE. Because completion ports are a Windows I/O construct
, if you call GetLastError or WSAGetLastError, the error code is likely to be 
a Windows error code and not a Winsock error code. To retrieve the equivalent 
Winsock error code, WSAGetOverlappedResult can be called specifying the socket
 handle and WSAOVERLAPPED structure for the completed operation, after which W
SAGetLastError will return the translated Winsock error code.

One final detail not outlined in the last two examples we have presented is ho
w to properly close an I/O completion port��especially if you have one or more
 threads in progress performing I/O on several sockets. The main thing to avoi
d is freeing an OVERLAPPED structure when an overlapped I/O operation is in pr
ogress. The best way to prevent this is to call closesocket on every socket ha
ndle��any overlapped I/O operations pending will complete. Once all socket han
dles are closed, you need to terminate all worker threads on the completion po
rt. This can be accomplished by sending a special completion packet to each wo
rker thread using the PostQueuedCompletionStatus function, which informs each 
thread to exit immediately. PostQueuedCompletionStatus is defined as

BOOL PostQueuedCompletionStatus(
    HANDLE CompletionPort,
    DWORD dwNumberOfBytesTransferred, 
    ULONG_PTR dwCompletionKey, 
    LPOVERLAPPED lpOverlapped
);
The CompletionPort parameter represents the completion port object to which yo
u want to send a completion packet. The dwNumberOfBytesTransferred, dwCompleti
onKey, and lpOverlapped parameters each will allow you to specify a value that
 will be sent directly to the corresponding parameter of the GetQueuedCompleti
onStatus function. Thus, when a worker thread receives the three passed parame
ters of GetQueuedCompletionStatus, it can determine when it should exit based 
on a special value set in one of the three parameters. For example, you could 
pass the value 0 in the dwCompletionKey parameter, which a worker thread could
 interpret as an instruction to terminate. Once all the worker threads are clo
sed, you can close the completion port using the CloseHandle function and fina
lly exit your program safely.

The completion port I/O model is by far the best in terms of performance and s
calability. There are no limitations to the number of sockets that may be asso
ciated with a completion port and only a small number of threads are required 
to service the completed I/O. For more information on using completion ports t
o develop scalable, high-performance servers, see Chapter 6.


--

�� ��源:��泉������ http://bbs.sdu.edu.cn [FROM: 202.194.32.132]