Socket synchronization, Asynchronization and blocking, non-blocking

Source: Internet
Author: User

Http://hj490134273.blog.163.com/blog/static/1446496162010494441182/

I just started to learn socket programming. I just made a simple chat room program. Later I went deep into it and found many problems, first, let's talk about the three socket usage methods (winapi socket, casyncsocket, and csocket) on the widows platform. First, let's talk about the differences between the four modes. I 've got to know about them by looking for information everywhere, recorded here:

 

   During network programming, we often see four call Methods: synchronous, asynchronous, blocking, and non-blocking. These methods are not easy to understand. The following is my understanding of these terms.

   
Synchronization and Asynchronization refer to the communication mode, while blocking and non-blocking refer to whether to wait until the action is completed before the response is returned. Therefore, the four words cannot be confused. Communication synchronization mainly refers to the next request sent by the client only after the server responds to the request. Therefore, all requests at this time will be synchronized on the server. The second is asynchronous communication. After the client sends a request, it can send the next request without waiting for the response from the server, in this way, all request actions will be asynchronous on the server. The request link is like a request queue, and all actions will not be synchronized here. In the implementation process, if the server side is asynchronous and the client side is asynchronous, the communication efficiency will be very high. However, if the server side returns a request to the request link, the client can be synchronized. In this case, the server is compatible with synchronization and Asynchronization. On the contrary, if the client is asynchronous and the server is synchronous, there will be no problem, but the processing efficiency is lower.

   
Blocking and non-blocking only apply to the reading and sending of requests.

 

   
Synchronization: Synchronization means that when a function call is sent, the call will not be returned until the result is obtained. According to this definition, most functions are called synchronously (such as sin and isdigit ). But in general, when we talk about synchronization and Asynchronization, we are referring to the tasks that require the collaboration of other components or a certain amount of time. The most common example is sendmessage. This function sends a message to a window. This function does not return a message before the recipient finishes processing the message. After the other party completes processing, this function returns the message processing function.
The lresult value is returned to the caller.

 

    Asynchronous: Asynchronous concept and synchronization relative. When an asynchronous process is called, the caller cannot obtain the result immediately. After the call is completedStatus,NotificationAndCallbackTo notify the caller. Take the casycsocket class as an example (note that csocket is derived from casyncsocket, but the function has been converted from Asynchronous to synchronous). When a client calls
After the connect function sends a connection request,The caller's thread can run down immediately.. After the connection is established, the socket underlying layer sends a message to notify the object.

   The Execution Component and caller can return results in three ways: Status, notification, and callback. Which one can be used depends on the implementation of the execution part, unless the execution part provides multiple options, it is not controlled by the caller. If you useStatusSo the caller needs to check the value of a variable at a certain time, and the efficiency is very low (some new programmers prefer to use a loop to check the value of a variable, this is actually a very serious error ). If you useNotificationThe efficiency is very high, because the execution parts almost do not need to do additional operations. AsCallbackFunctions are actually not much different from notifications.

      Both synchronous and asynchronous are only applicable to local socket      In synchronous mode, for example, reciev and send, make sure that the response is received or sent. Continue to execute the following code.      Otherwise, the thread is usually used for processing in synchronization mode.      The asynchronous mode is different. No matter whether the code is received or sent out, the system immediately returns the result and continues to execute the following code. The result is a Message notification. 

    Blocking: Blocking call refers to the process before the call result is returned,The current thread will be suspended. The function is returned only after the result is obtained.

Some people may equate blocking calls with synchronous calls. In fact, they are different. For synchronous calls, the current thread is still activated in many cases, but the current function does not return logically.. For example, we call the receive function in csocket. If there is no data in the buffer zone, this function will wait until data is returned. At this time, the current thread will continue to process a variety of messages. If the main window and the calling function are in the same thread, the main interface should be refreshed unless you call the function in special interface operations. Another function Recv used by socket to receive data isBlocking call. When the socket works in blocking mode, if the function is called without data, the current thread will be suspended until there is data.

 

   Non-blocking: The concept of non-blocking corresponds to blocking, which means that the function will not block the current thread and return immediately before the result cannot be obtained immediately. There is a strong correlation between the blocking mode of objects and the blocking mode of function calling objects, but it is not one-to-one.

   【Blocking objects can have non-blocking calling methods. We can use certain APIs to poll the status and call the blocking function as appropriate to avoid blocking. For non-blocking objects, calling special functions can also be blocked. The select function is an example. Blocking communication improves performance in many systems through overlapping communication and computing. An intelligent communication controller automatically executes communications. Light-heavy evidence is a mechanism to achieve such overlap. An optional mechanism that causes good performance is non-blocking communication. A blocked sending starts to call the initialization of this sending operation, but it cannot be completed. Before the message is copied from the sending cache, the call to start sending will be returned. An independent "sending completed" call is required to complete the communication, for example, to check the data copied from the sending cache. With appropriate hardware, after the sender is initialized and before it is completed, data conversion from the sender's storage can be performed simultaneously with the computation completed by the sender. Similarly, a non-blocking "receive start call" initializes the receiving operation,
But cannot complete it. Before a message is stored in the receiving cache, this call will return. An independent "receive completed" call is required to complete the receiving operation and check the received data cached. With appropriate hardware, after receiving operation initialization and before it completes, the data stored in the receiver can be converted at the same time as the computing. The use of non-blocking reception can avoid system caching and copying from memory to memory even though information is provided earlier in the receiving cache location. The non-blocking sending start call can use the same four modes as blocking sending: Standard, cache, synchronization, and preparation modes. These have the same meaning. No matter whether a matching recipient is logged on or not, you can start sending in all modes except "prepared". If one matching recipient is logged on, you can start sending in a non-blocking "prepared" mode. In all cases, the start call of sending is local: no matter the status of other processes, it immediately returns. If this call causes some system resources to run out, it will fail and return an error code. High-quality MPI implementation should ensure that this situation only occurs when it is "Diseased. That is, one MPI implementation will support a large number of pending non-blocking operations. When the data has been copied from the sending cache, this sending completion call is returned. It can have additional meaning, depending on the sending mode. If the sending mode is "synchronous", only one matching recipient can complete the sending. That is, a receiver has been logged on and matched with the sender. In this case, the call to the sending completion is non-local. Note: If a synchronous, non-blocking message matches a non-blocking message before the call is completed,
It can be done. (Once the sender "knows" the conversion will end, it will be able to complete, but before the receiver "knows" the conversion will end ). If the sending mode is "cached" and the message is not suspended, the message must be cached. At this time, the sending completion call is local, and it must be successful regardless of the status in which a request is received. If the sending mode is standard and the message is cached, the sending end call can be returned before a matching message is received. On the other hand, sending is complete until a matching message is received, and the message has been copied to the receiving cache. Non-blocking sending can be matched by blocking receiving, or vice versa. Suggestions to the user. The sending operation is completed, and the standard mode can be delayed, and the same mode must be delayed,
Until a matched logon request is received. In both cases, the use of non-blocking sending allows the sender to proceed ahead of the receiver, so that the calculation of the speed of the two processes is more tolerant of fluctuations. Non-blocking sending in cache and readiness modes has a limited impact. One possible non-blocking message will be returned, and one blocking message will be returned after the data is copied from the sender's storage. As long as data copying can be the same as computing, the use of non-blocking transmission has advantages. The message sending mode implies that communication is initiated by the sender. When the sender initializes the communication (data is directly moved to the receiving cache and does not need to queue a pending sending request), if the receiving has been logged in, this communication will generally have a low extra burden. However, only after a matched message has been sent can one receive operation be completed. When the non-blocking receiving waits for sending, there is no blocking receiving, and its use allows an additional burden of low communication .]

 

Synchronization analogy:

   We know that in socket transmission, TCP transmission is used as an example. Assume that serverClient B for communication and transmission. First, you must create a listening thread on host. To listen to a port, machine B can send a communication request to machine A. Machine B is connected to machine. Server A can obtain a listener object from its listening queue. You can receive and send data when you get this socket object on Client. This problem occurs. If the request is successful at Client A, end B sends a piece of data. Then, end a can obtain the information of the socket object directly. However, if the B end does not directly send the information after the connection is successful, it will send the information within the uncertain time. Then end a cannot obtain this information. Generally, a timer is used to scan the data cache. Check whether data exists, which is very inefficient. So how can we solve this problem. We use asynchronous transmission. The principle of asynchronous transmission is. After the socket object is obtained on end a, a callback function is created instead of directly receiving data. The callback function is maintained by the system. It automatically scans the data storage area at the specified time. If there is data, the data is stored in the specified byte array. You do not have to worry about it yourself. 
    So what is the difference between synchronous and asynchronous? Assume that the user's socket connection data is relatively short. If data is directly sent by one connection or the client is relatively small, use synchronization. If your socket is connected for a long time, use asynchronous mode!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.