This paper mainly analyzes several kinds of socket programming modes. Mainly includes basic blocking sockets, nonblocking sockets, I/O multiplexing. Of these, blocking and non-blocking are relative to sockets, while others are essentially socket-based concurrency patterns. I/O multiplexing is the main analysis of common models under Linux and Windows. Finally, compare the advantages and disadvantages of these sockets, and discuss the use of multi-threading and socket and the common mode of server development.
blocking Mode
Blocking mode is the most basic socket programming model and is an example of getting started in various books on network programming. As its name says, blocking mode sockets block the current thread until the result is returned, otherwise it waits.
non-blocking mode
nonblocking mode is a relative blocking mode in which the socket does not block the current thread, and non-blocking mode does not wait for the result to return, but it runs immediately.
// set socket to non-blocking mode // O_nonblock Flag Setting non-blocking mode
It is important to note that the difference between blocking/non-blocking, synchronous/asynchronous. In essence, they are different. Synchronous and asynchronous are relative operation results and will not wait for results to return. Blocking and non-blocking are relative to whether the thread is blocked. In fact, there are essential differences between the two, and their modified objects are different. Blocking and non-blocking refers to the data that the process accesses if it is not already in place, whether the process needs to wait, simply saying that this is equivalent to the implementation difference within the function, which is whether to return directly or wait for it to be ready. While synchronous and asynchronous refers to the mechanism of accessing data, synchronization generally refers to the active request and wait for the completion of the I/O operation, when the data is ready to be blocked when reading and writing, asynchronous refers to the active request of data can continue to process other tasks, and then wait for I/O, operation completed notification, This allows the process to read and write data without blocking. Because the two are often the same in performance, they are often confused.
I/O multiplexing
I/O multiplexing is a concurrent server development technique that handles multiple client connections. With this technology, the system core buffers I/O data, and when an I/O is ready, the system notifies the application that I/O is readable or writable so that the application can complete the appropriate I/O immediately without waiting for the system to complete the appropriate I/O operations, so that the application does not have to wait for I/O operations to block.
Under Linux, there are three models of select, poll and Epoll, and under FreeBSD there are KQUEUE,WINDWOS Select, event selection model, overlapped I/O and completion port.
I/O multiplexing model on LinuxSelect
select essence is the next process by setting or checking the data structure that holds the FD flag bit. Select is processed by polling the FD collection.
// select-related function int select (int MAXFDP1, Fd_set *readset, fd_set *writeset, Fd_set *exceptset,const struct timeval *timeout) // return value: Number of ready descriptors, time-out returned 0, error returned-1 void Fd_zero (Fd_set *fdset); // void fd_set (int FD, fd_set *fdset); // Adds a given file descriptor to the collection void fd_clr (int FD, fd_set *fdset); // int fd_isset (int FD, fd_set *fdset); //
However, select has a certain flaw. The number of FD that a single process can monitor is limited, and Linux generally is 1024. Although it can be modified, there is always a limit. Each time a select is called, the FD collection needs to be copied from the user state to the kernel state, and the entire FD collection needs to be looped, which is a lot more expensive.
Poll
The implementation of poll is very similar to select, essentially the same, and only describes the FD collection in different ways. Poll are stored based on a linked list. Although there is no limit to the maximum number of connections, there is still the overhead associated with the FD collection copy and loop. And poll also has a feature is the level trigger, the kernel notifies the FD, is not processed, then the kernel will be kept informed until it is processed.
// poll correlation Function int poll (struct POLLFD *fdarray, unsigned long nfds, int timeout);
Epoll
Epoll is an improvement on select and poll. Compared to Poll,epoll using "event" ready notification, through EPOLL_CTL to register FD, once the FD is ready, the kernel will use a similar callback callback mechanism to activate the FD, put ready FD into the Ready list, and wake up in the Epoll_ Wait in the process of sleep, so that does not need polling, to determine whether the FD aggregate collection is empty. and epoll not only supports horizontal triggering, it also supports edge triggering. Edge triggering is when the kernel notifies FD, regardless of whether it is not processed at the notification. On the set of the storage FD, Epoll also uses a better mmap, and will guarantee that the FD collection copy will only occur once.
// epoll Correlation function // Handle creation int epoll_ctl (int epfd, int op, int fd,// event Register int epoll_wait (int epfd, struct Epoll_event * events, int maxevents// waiting for events to occur
I/O multiplexing model on WindowsEvent Selection Model
The event selection model is message-based. It allows the program to receive event-based network event notifications through the socket.
// Event Selection model correlation function Wsaevent wsacreatevent (void); // Create event Object int WSAEventSelect (SOCKET s, wsaevent heventobject,long // associated event
overlapped I/O model
The overlapped I/O model is an asynchronous I/O model. The core of an overlapping model is an overlapping data structure. The overlapping model is to have the application use overlapping data structures (wsaoverlapped) to post one or more Winsock I/O requests at a time. If you want to use the file in overlapping ways, you must open it with the FILE_FLAG_OVERLAPPED flag. When the I/O operation is complete, the system notifies the application. With the overlapped I/O model, the application only needs to wait for the I/O operation to complete after the I/O function is called.
NULL NULL);
Completion Port model (IOCP)
The IOCP completion port is currently the best I/O model under Windows and is, of course, the most complex. Simply put, IOCP is a high-performance I/O model that is a mechanism for applications to use the thread pool to process asynchronous I/O requests. IOCP All user requests are posted to a message queue, and the threads in the thread pool remove the messages from the message queue and process them one at a time to avoid being able to thread each of the I/O requests. Not only reduce the resources of the thread, but also improve the utilization of the thread.
//IOCP Simple process//Create completion PortPort port = CreateIoCompletionPort (invalid_handle_value, 0, 0,Fixedthreadcount ());//associating a socket to a IOCPCreateIoCompletionPort (HANDLE) M_SOCKCLIENT,M_HIOCP,(ULONG_PTR) m_sockclient, 0);//Post AcceptEx RequestLpfn_acceptex M_lpfnacceptex;//AcceptEx function PointerGUID Guidacceptex = Wsaid_acceptex;//GUID, this is required to identify the AcceptEx function.DWORD dwbytes = 0; WSAIoctl (M_plistencontext->m_socket,Sio_get_extension_function_pointer, &guidacceptex,sizeof(Guidacceptex), &m_lpfnacceptex,sizeof(M_lpfnacceptex), &dwbytes,NULL,NULL);//using GetQueuedCompletionStatus () to monitor the completion portvoid *lpcontext =NULL; OVERLAPPED*poverlapped =NULL; DWORD dwbytestransfered= 0; BOOL Breturn=GetQueuedCompletionStatus (Piocpmodel->m_hiocompletionport, &dwbytestransfered,(Lpdword)&lpcontext, &poverlapped,INFINITE);//Receive notificationint nbytesrecv = WSARecv (Piocontext->m_socket, Piocontext->p_wbuf,1, &dwbytes, 0, PIoContext->p_ol,NULL);
Use of Threads
In the discussion of the above I/O reuse model, the use of threads is actually included. Overlapping I/O and I/OS completion ports are all leveraging threads. It can also be seen in the development of high concurrent servers, the adoption of threading is also very necessary. In the use of I/O completion ports, the thread pool is also used, which is now widely used. Through the thread pool, you can reduce the overhead associated with creating threads frequently.
Generally using Windows to provide I/O models under Windows is sufficient to cope with many scenarios. However, the I/O model under Linux is not related to threads. Sometimes for higher performance, the thread pool and the I/O multiplexing model are also used together. For example, many Linux service-side programs take the form of epoll and thread pooling, and of course the introduction of threading also brings more complexity, requiring attention to thread control and performance overhead (the thread's main overhead is switching on threads). And Epoll is also good enough, so only with Epoll is also possible, like Libevent this famous network library is also adopted epoll implementation. Of course, under Linux There are also only multi-process or multi-threaded to achieve concurrency. This will bring a certain disadvantage, the program needs to maintain a large number of scoket. In the server development of the use of threads, but also to ensure that no lock, lock is also a high cost.
Socket programming pattern understanding and comparison