Reprint please indicate source: http://blog.csdn.net/caoshiying?viewmode=contents
First, review the overlapping IO model
Using a completion routine to implement overlapped I/O is much simpler than using event notifications. In this model, the main thread only uses the constant acceptance of the connection; The worker thread determines whether a new client connection is established, if any, activates an asynchronous WSARECV operation for that client socket, and then calls SleepEx to put the thread in a warning wait state so that the i/ o After completion completionroutine can be called by the kernel. If the worker thread does not call SleepEx, the kernel cannot invoke the completion routine after the I/O operation is completed (because the completion routine should be running the same thread as the code that activated the WSARecv asynchronous operation).
The implementation code in the completion routine is simple, it takes out the received data, then sends the data intact to the client, and finally activates another WSARECV asynchronous operation. Note that "trailing data" is used here. When we call WSARecv, the parameter lpoverlapped actually points to a much larger structure per_io_operation_data, which, besides wsaoverlapped, is appended with the structure information of the buffer, Also includes client sockets
Important information such as the word. Thus, in the completion routine through the parameter lpoverlapped get not only the wsaoverlapped structure, there is a trailing behind the client socket and receive data buffer and other important information. This C language technique is also used when I introduce the completion port.
Second, complete the port model
The complete port model is by far the most complex I/O model. However, if an application needs to manage a large number of sockets at the same time, the best system performance can often be achieved by using this model! Unfortunately, the model is only available for Windows NT and Windows 2000 operating systems. Because of the complexity of the design, you should consider using the "completion port" model only if your application needs to manage hundreds of or even thousands of sockets at the same time, and you want the performance of your application to increase linearly as the number of CPUs installed in the system increases. One basic guideline to keep in mind is that if you are developing high-performance server applications for Windows NT or Windows 2000 and want to serve a large number of socket I/O requests (Web servers are a typical example of this), the I/O completion port model is the best choice!
The completion port model is one of my favorite models. Although its implementation is more complex (in fact, I think its implementation is much simpler than the overlapped I/O implemented with event notification), but its efficiency is amazing. When I was in T company, I helped colleagues write a performance test program for a mail server, with the completion port model. The results show that the completion port model can achieve very high throughput in the case of multiple connections (tens of thousands), relying on only one or two worker threads.
Three, the key function
1, CreateIoCompletionPort
Creates an input/output (I/O) completion port and associates it with a specified file handle, or creates an I/O completion port that is not already associated with a file handle, allowing for association at a later time. Associates an instance of an open file handle with an I/O completion port, allowing a process to receive notification of completion of an asynchronous I/O operation that contains the file handle. Note: The term file handle used here refers to a system abstraction that represents an overlapped I/O endpoint, not just a file on disk. Any system object supports overlapping I/o-such network endpoints, TCP sockets, Named Pipes, and mail slots that can be used as file handles.
Function Prototypes:
HANDLE WINAPI createiocompletionport ( _in_ HANDLE filehandle, _in_opt_ HANDLE Existingcompletionport, _in_ ulong_ptr completionkey, _in_ DWORD numberofconcurrentthreads) ;
Function parameters:
FileHandle: An open file handle or Invalid_handle_value. This file handle must be an object that supports overlapping IO. If a handle is provided, it must be a handle that has been opened to the overlapped I/O model completion port. For example, if you use the CreateFile function to get a handle, you must specify the FILE_FLAG_OVERLAPPED flag in the parameter when you call this function. If Invalid_handle_value is specified, then the function creates an IO completion port model with no associated file handle, and the Existingcompletionport parameter must be set to Null,completionkey parameter to be ignored.
Existingcompletionport: Is the completion port that already exists. If NULL, a new IOCP is created.
Completionkey: The user-defined handle contains the I/O completion package information. This parameter is ignored when FileHandle is set to Invalid_handle_value.
NumberOfConcurrentThreads: The maximum number of threads that the operating system can allow to process I/O completion packets for the I/O completion port at the same time. If the Existingcompletionport parameter is not empty, this parameter is ignored. If this parameter is zero, the system allows multiple threads to run concurrently because the processor is in the system.
return value:
If the function succeeds, the return value is a handle to the I/O completion port: If the Existingcompletionport parameter is empty, the return value is a new processing. If the Existingcompletionport parameter is a valid I/O completion port handle, the return value is the same processing. If the file handle parameter is a valid processing, the file processing is now with the returned I/O completion port. If the function fails, the return value is null. To get more error information, call the GetLastError function.
2, GetQueuedCompletionStatus
The disappointment is that Microsoft's official MSDN does not provide instructions for this API. The following references an English document for translation. The document says this function attempts to complete the port with an I/O completion package from the specified I/O. If the packet queue is not completed, the function waits for the completion of a pending I/O operation associated with the completion port.
Function Prototypes:
BOOL WINAPI getqueuedcompletionstatus ( _in_ HANDLE completionport, _out_ lpdword Lpnumberofbytes, _out_ pulong_ptr lpcompletionkey, _out_ lpoverlapped *lpoverlapped, _In_ DWORD dwmilliseconds);
Function parameters:
Completionport: Handle to the completion port. Create a completion port, using the CreateIoCompletionPort function.
Lpnumberofbytes: A pointer to a variable that points to the number of bytes transferred during a completed I/O operation.
lpCompletionKey: Pointer to the variable that is associated with the file handle for the completion key, and the I/O operation for the key is complete. One key to completion is the key to each file, which is to designate a named CreateIoCompletionPort.
lpoverlapped: A pointer to a variable that points to the address of the overlapped structure specified at the beginning of the completed I/O operation. Even if you have passed a file handle associated with the completion port and a valid overlapping structure, the application can prevent port notifications from being completed. This is done by specifying the overlapping structure of the Hevent member for effective event processing and setting its low-order. A valid event handle whose low-order setting will keep I/O complete from being queued to the completion port.
Dwmilliseconds: The number of milliseconds that the caller is willing to wait for a completion packet to occur on the completion port. If a completion package does not appear within the specified time, the function times out, returns false, and sets *lpoverlapped to null. If the argument is infinite, the function will have no time. If the parameter is zero and there is no I/O operation in the dequeue, the function cancels the wait time and immediately operates.
return value:
Returns a non-0 (true) if successful or 0 (false), otherwise. To get more error messages, call GetLastError.
This feature associates a thread with the specified completion port. A thread can be associated with at most one completion port. If the call to call GetQueuedCompletionStatus fails because the completion port handle is closed with it, the function returns false,*lpoverlapped will be empty, GetLastError will return error_abandoned_ Wait_0.
Windows Server 2003 and Windows XP: Closing the completion port handle, calling excellent does not cause previous behavior. The function will continue to wait until an item is removed from the port or until a timeout occurs, if the value is not specified.
If the GetQueuedCompletionStatus function call succeeds, it is out of the package to complete a successful I/O operation to complete the port and the variables that store the information point to the following parameters: Lpnumberofbytes,lpcompletionkey, and lpoverlapped. In the failure (the return value is wrong), these same parameters can contain a specific combination of values as follows:
If *lpoverlapped is empty, the feature does not dequeue the completion port from the completion package. In this case, the function does not store information in the parameter pointed to by Lpnumberofbytes and lpCompletionKey, whose value is indeterminate.
If the *lpoverlapped is not empty and the function presses the completion port of a failed I/O operation to complete the functionality of the package, store information about the lpCompletionKey lpoverlapped lpnumberofbytes that the variable that failed the operation points to. To get more error messages, call GetLastError.
3, PostQueuedCompletionStatus
Sends an I/O completion packet to an I/O completion port. The I/O completion package will satisfy an excellent call to the GetQueuedCompletionStatus function. The function returns a three-value pass for the second, third, and fourth parameters of the PostQueuedCompletionStatus call. The system does not use or validate these values. In particular, the lpoverlapped parameter does not require a point overlapping structure.
Function Prototypes:
BOOL WINAPI postqueuedcompletionstatus ( _in_ HANDLE completionport, _in_ DWORD dwnumberofbytestransferred, _in_ ulong_ptr dwcompletionkey, _in_opt_ lpoverlapped lpoverlapped);
Parameters:
Completionport: A handle to the I/O completion port of an I/OS completion packet.
Dwnumberofbytestransferred: The value to be returned by the lpnumberofbytestransferred parameter GetQueuedCompletionStatus function. 0xFFFFFFFF means that all trailing data is processed. Do this only when you are ready to close the port.
Dwcompletionkey: The value that can be returned by the GetQueuedCompletionStatus function lpCompletionKey parameter.
lpoverlapped: The value to be returned by the lpoverlapped parameter GetQueuedCompletionStatus function.
return value:
If the function succeeds, the return value is non-zero. If the function fails, the return value is zero. To get more error messages, call GetLastError.
Iv. Complete Sample Program
Then the above several socket articles are written, about the common code and the reflective client see: A simple selection model of the socket programming model. Here is the new Overlapped_server project, a new Overlapped_server_manager type, inherited from the Iserver_manager interface, the complete code of the header file is as follows:
#pragma once#define socket_message_size 1024#include <WinSock2.h> #include <common_callback.h>typedef Enum{recv_posted}operation_type;typedef struct{wsaoverlapped overlap; Wsabuf Buffer;char message[socket_message_size];D word received_count;dword flags;operation_type OPERATION_TYPE;} Peerio_operation_data, *lppeerio_operation_data;class completeio_server_manager:public iserver_manager{private: int Iport;int Iaddr_size;common_callback callback; BOOL brunning; SOCKET server; Wsadata Wsadata; HANDLE Hcomplete_port; System_info System_info; Lppeerio_operation_data peer_data;bool Bdisposed;protected:bool accept_by_crt (); bool Accept_by_winapi ();p ublic: void receive (), void shutdown (), void start_receive (), void Start_accept ();p Ublic:completeio_server_manager (), virtual ~completeio_server_manager ();};
The implementation file complete code is as follows:
#include "completeio_server_manager.h" #include <stdio.h> #include <tchar.h>completeio_server_manager:: Completeio_server_manager () {iport = 5150;iaddr_size = sizeof (sockaddr_in); brunning = FALSE; GetSystemInfo (&system_info); Callback.set_manager (this); Callback.set_receive_thread_coount (system_ info.dwnumberofprocessors); hcomplete_port = CreateIoCompletionPort (Invalid_handle_value, NULL, 0, 0); bdisposed = false;} Completeio_server_manager::~completeio_server_manager () {if (bdisposed) shutdown ();} BOOL Completeio_server_manager::accept_by_crt () {return true;} BOOL Completeio_server_manager::accept_by_winapi () {sockaddr_in server_addr; Sockaddr_in client_addr; SOCKET client; Lppeerio_operation_data Peer_data;int iresult =-1; WSAStartup (Makeword (2, 2), &wsadata); server = socket (af_inet, sock_stream, ipproto_tcp); server_addr.sin_addr. S_un. S_ADDR = htonl (inaddr_any); server_addr.sin_family = Af_inet;server_addr.sin_port = htons (iport);d O{iresult = bind ( Server, (struct sockaddr*) &serveR_ADDR, iaddr_size); if (Iresult = = socket_error) {iport++;server_addr.sin_port = htons (Iport);}} while (Iresult = =-1), Listen (server, 3);p rintf ("The socket server based on the completion port model started successfully. The listening port is:%d\n ", Iport); while (brunning) {printf (" starts listening for requests.) \ n "); client = accept (server, struct sockaddr*) &client_addr, &iaddr_size); if (client = = Socket_error) continue; printf ("New Client Connection:%s:%d\n", Inet_ntoa (CLIENT_ADDR.SIN_ADDR), htons (Client_addr.sin_port)); CreateIoCompletionPort (HANDLE) client, Hcomplete_port, (DWORD) client, 0);p Eer_data = (lppeerio_operation_data) HeapAlloc (GetProcessHeap (), heap_zero_memory, sizeof (peerio_operation_data));p Eer_data->buffer.len = SOCKET_ Message_size;peer_data->buffer.buf = Peer_data->message;peer_data->operation_type = RECV_POSTED;printf (" Begins receiving client transfer data. \ n "); WSARecv (client, &peer_data->buffer, 1, &peer_data->received_count, &peer_data->flags, & Peer_data->overlap, NULL);p rintf ("Received client data. \ n ");} return true;} void Completeio_server_manager::receive () {DWORD Dwtransfered = 0; SOCKET client; Lppeerio_operation_data peer = nullptr;while (brunning) {printf ("Thread:%d", querying port status information.) \ n ", GetCurrentThreadID ()); GetQueuedCompletionStatus (Hcomplete_port, &dwtransfered, (pulong_ptr) &client, (LPOVERLAPPED*) &peer, INFINITE);p rintf ("Get port information. \ n "), if (dwtransfered = = 0xFFFFFFFF) return;if (Peer->operation_type = = recv_posted) {if (dwtransfered = = 0) { Closesocket (client);p rintf ("There are clients exiting. \ n "); HeapFree (GetProcessHeap (), 0, peer);} Else{peer->message[dwtransfered] = 0;send (client, peer->message, dwtransfered, 0); memset (peer, 0, sizeof (Peerio _operation_data));p Eer->buffer.len = Socket_message_size;peer->buffer.buf = peer->message;peer-> Operation_type = recv_posted; WSARecv (client, &peer->buffer, 1, &peer->received_count, &peer->flags, &peer->overlap, nullptr);}}} void Completeio_server_manager::shutdown () {postqueuedcompletionstatus (hcomplete_port, 0xFFFFFFFF, 0, NULL);// Port trailing data. brunning = False;callback.shutdown ();//Sweep CLosehandle (Hcomplete_port); closesocket (server); WSACleanup (); bdisposed = true;} void Completeio_server_manager::start_accept () {brunning = true;bdisposed = False;callback.start_accept_by_winapi ();} void Completeio_server_manager::start_receive () {brunning = true;bdisposed = False;callback.start_receive ();} int main () {Completeio_server_manager csm;csm.start_accept (); csm.start_receive ();p rintf ("The server started successfully. Press any key to close the server and exit the program. \ n "); GetChar (); Csm.shutdown (); return 0;}
Five, the effect
Six, experience
Once you have successfully created a completion port, you can begin associating the socket handle with the object. Before associating sockets, however, you must first create one or more worker threads to service the completion port after I/O requests are posted to the completion port object. At this point, you might wonder how many threads should be created to serve the completion port? This is actually a very complex aspect of completing the port model, because the amount of service I/O requests depends on the overall design of the application.
One important thing to keep in mind here is that the number of concurrent threads that we specify when we call CreateIoCompletionPort is not the same as the number of worker threads that we intend to create. Earlier, we suggested that you use the CreateIoCompletionPort function to specify a thread for each processor (the number of processors to specify how many threads) to avoid the frequent threading "scene" switching activity, which can affect the overall performance of the system. The numberofconcurrentthreads parameter of the CreateIoCompletionPort function explicitly indicates that the system: on a completion port, only n worker threads are allowed to run at a time. If the number of worker threads created on the completion port exceeds n, only n threads are allowed to run at the same time.
In practice, however, the system may exceed this value for a short period of time, but it will soon be reduced to the value set in the CreateIoCompletionPort function in advance. So why is it that the number of worker threads actually created is sometimes more than the CreateIoCompletionPort function sets? Is it necessary to do so? As mentioned earlier, this depends primarily on the overall design of the application. Suppose one of our worker threads invokes a function, such as sleep or WaitForSingleObject, but enters a paused (locked or suspended) state, allowing another thread to take its place. In other words, we want to be able to execute as many threads as possible at any time; Of course, the maximum number of threads is set in advance in the CreateIoCompletionPort call.
In this way, if you anticipate that your thread is likely to be temporarily paused, it is best to create a thread that is more than the value of the NumberOfConcurrentThreads parameter of CreateIoCompletionPort so that the potential of the system can be fully exerted. Once you have enough worker threads on the completion port to service an I/O request, you can start associating the socket handle with the completion port. This requires that we call the CreateIoCompletionPort function on an existing completion port, while for the first three parameters--filehandle,existingcompletionport and completionkey-- Provides information for sockets. Where the FileHandle parameter specifies a socket handle to be associated with the completion port. The Existingcompletionport parameter specifies an existing completion port.
The Completionkey (finish key) parameter specifies the "handle data" to be associated with a particular socket handle, in which the application can save any type of information corresponding to a socket. It is called a "handle data" because it corresponds only to the data associated with that socket handle. It can be used as a pointer to a data structure to hold the socket handle, and in that structure, it contains the handle of the socket and other information related to that socket.
Completion port model of the socket programming model