Synchronous and asynchronous Functions

Source: Internet
Author: User

ArticleSource: http://blog.163.com/lyzaily@126/blog/static/42438837200952751954922/

 

1. synchronous and asynchronous Functions

What is a synchronous function?

What is an asynchronous function?

What is the impact on the thread when they are executed in the thread?

How can a thread synchronize with an asynchronous function?

According to Microsoft's explanation on msdn:

(1) Synchronous function: When a function is executed synchronously, it will not be returned immediately when the function is called until all the work done by the function is completed.

(2) asynchronous function: if an asynchronous function is called, the function returns immediately even if the operation task specified by the function is not completed.

(3) How does calling the above two functions in one thread affect the calling thread?

When a thread calls a synchronous function (for example, this function is used to complete file writing tasks), if the function does not complete the specified operation immediatelyThis operation will cause the call thread to be suspended.(Assign the CPU usage right to the system for other threads to use),Only after the operation specified by the synchronous function is completed can the call thread be rescheduled.

When a thread calls an asynchronous function (for example, this function is used to complete file writing tasks), the function immediately returns the result even though the specified task has not been completed, in this way, the thread will execute the next statement of the asynchronous function without being suspended. How is the work specified by this asynchronous function completed? Of course it is done through another thread. Where does the new thread come from?It may be a newly created thread in an asynchronous function or a prepared thread in the system..

(4) How can a thread that calls asynchronous functions synchronize the execution results of asynchronous functions?

To solve this problem, the call thread needs to useWait FunctionTo determine when the asynchronous function has completed the specified task. Therefore, after a thread calls an asynchronous function, it immediately calls a "wait function" to suspend the call thread and waits until the asynchronous function completes all its operations before executing the next instruction in the thread.

Have we found an interesting place ?! That is, we can use the wait function to encapsulate an asynchronous function into a synchronous function.

 

2. synchronous and asynchronous calls

The operating system has been very sophisticated today, and threads are one of the masterpiece. The operating system divides the CPU processing time into many short time slices. At time t1, it executes the instruction of a thread, and at time t2, it executes the instruction of the next thread, and each thread executes the instruction in turn, the result is that all threads are working side by side. In this way, multiple threads can be created during programming and executed during the same period. Each thread can perform different tasks in parallel.
In the single-threaded mode, a computer is a strictly von noriman machine.CodeWhen calling another piece of code, you can only use synchronous calls. You must wait for the code to run and return the result before the call can continue. With multi-thread support, asynchronous calls can be used. The caller and the called can belong to two different threads. After the caller starts the called thread, wait until the other party returns the result to continue executing the subsequent code. After the called party completes the execution, notify the caller through some means: the result has come out, please handle it as appropriate.
Some processing on the computer is time-consuming. When calling this processing code, if the caller is standing there, it will seriously affect Program Performance. For example, if a program needs to open a file to read the data and perform initialization based on the data, the main window of the program will be delayed, it makes the user feel that the program is too bad to wait for a long time. Asynchronous calling can easily resolve the problem: Put the entire initialization process into a separate thread, and the main thread starts the thread and then goes down, so that the main window is instantly displayed. When the user is staring at the window, the initialization process is quietly completed. After the program starts to run stably, you can continue to use this technique to improve the instantaneous response of human-computer interaction. When you click the mouse, if the operation is time-consuming, clicking the mouse will not immediately respond, and the entire program looks very heavy. With the help of asynchronous calls for processing time-consuming operations, the main thread can wait for the next message at any time. When you click the mouse, it is easy and quick, and it will certainly feel good about the software.
Asynchronous calls are especially effective for processing data from external inputs. If the computer needs to request data from a low-speed device, and then a lengthy data processing process, it is obviously difficult to use synchronous calls: The computer sends a request to the external device and then waits for data input; after an external device sends data to a computer, it also needs to wait for the computer to complete data processing before sending the next data request. Both parties have a waiting period, stretching the entire processing process. In fact, a computer can send a data request before processing the data, and then process the data immediately. If data processing is faster than data collection, only computers are waiting. external devices can continuously collect data. If a computer connects multiple input devices at the same time, it can send data requests to each device in turn and process the data sent from each device at any time. The entire system can maintain continuous and high-speed operation. The key to programming is to assign the data request code and Data Processing code to two different threads respectively. The data processing code calls a Data Request asynchronous function and then processes the data on hand. When the next group of data arrives, the data processing thread will receive a notification and end
Wait Status, send the next data request, and then continue to process the data.
During asynchronous calls, the caller turns around and leaves without waiting for the caller to return the result. Therefore, there must be a mechanism to notify the caller when the caller has the result. In the sameProcessThere are many methods that can be used. The commonly used methods are callback, event object and message.
Callback:
The callback method is simple: when an asynchronous function is called, a function address is put in the parameter, and the asynchronous function saves the address. After the result is returned, the function can be called back to send a notification to the caller. If an asynchronous function is encapsulated into an object, you can replace the callback function address with an event and send a notification to the caller through the event processing routine.
Event : Event is a common synchronization object provided by Windows system to align steps between different threads in asynchronous processing. If the caller has nothing to do for the time being, you can call the wait function and so on. At this time, the event is in the nonsignaled state. After the result is obtained by the called party, the event object is placed in the signaled state, and the wait function automatically ends the wait, causing the caller to re-act and retrieve the processing result from the called party. This method is more complicated than the callback method, and the speed is relatively slow. However, it has a great deal of flexibility and can be used to adapt to complicated processing systems.

Message: Sending Notifications via Windows is a good option, which is simple and secure. The program defines a user message and the caller prepares a message processing routine. The called party sends the message to the caller immediately after the result is obtained, and the result is sent through the wparam and lparam parameters. Messages are always associated with window handle. Therefore, the caller must use a window to receive messages, which is inconvenient. In addition, message contact affects the speed. Callback is more advantageous when high-speed processing is required.
If the caller and the called party belong to two different processes, Windows message sending is generally simple and reliable due to the memory space gap, the called party can transmit data to the caller by means of the message itself. Event objects can also be shared among different processes by name, but only notifications can be sent, and data cannot be transmitted, the use of Memory sharing methods such as Windows messages and filemapping, or the use of Mailslot and pipe communication means is required.
The asynchronous calling principle is not complicated, but it is easy to cause some inexplicable problems in actual use. In particular, it is prone to problems when different threads share code or share data. During programming, you must always pay attention to whether such a sharing exists, and various status signs are used to avoid conflicts. The mutex object provided by Windows is especially convenient here. Mutex can only have one owner at a time. After one thread gives up its jurisdiction, the other thread can take over. When a thread takes over the mutex before it is executed in the sensitive zone, other threads are blocked by the wait function. After the thread leaves the sensitive zone, it immediately gives up its jurisdiction and ends the wait function, another thread has the opportunity to visit this sensitive area. This effectively prevents multiple threads from entering the same sensitive zone.
As asynchronous calls are prone to problems, it requires a lot of experience to design a secure and efficient programming solution, so it is best not to abuse asynchronous calls. After all, synchronous calling makes people more comfortable: No matter where the program goes, as long as you stare at the moving point, you can be aware of it. As with asynchronous calling, there is always a feeling of mutual defeat and anxiety. When necessary, you can even convert an asynchronous function to a synchronous function. The method is simple: Call the asynchronous function and immediately call the wait function. Wait until the asynchronous function returns the result and continue.

 

3. How to Write an asynchronous Function

Almost all of the functions we write by programming are synchronously called functions. So how do we write an asynchronous function ?! I think this question may be a question raised by programmers who prefer professional research or people with special research spirit! Many of us are used to some asynchronous mechanisms provided by the Windows system. Using these asynchronous mechanisms, we can quickly implement some asynchronous operations and even easily implement a function that is executed asynchronously; but have we studied the nature of implementing an "Asynchronous function ?!

In a single-threaded system, the command execution is sequential, which implies that if function a calls function B, then, a must wait until B executes the remaining code in.

In multithreading, if we have a threada thread that calls a function C, and the C function we want to Implement Asynchronous execution, asynchronous execution must be supported by multiple threads. If we write a program in Windows, it is very easy to create a thread.

Handle winapi createthread (

_ In_opt lpsecurity_attributes lpthreadattributes,

_ In size_t dwstacksize,

_ In lpthread_start_routine lpstartaddress,

_ In_opt lpvoid lpparameter,

_ In DWORD dwcreationflags,

_ Out_opt lpdword lpthreadid );

Function to create a thread.

 

We can implement an asynchronous funcc function as follows:

(1) first write the work that you want to complete asynchronously to the function separately, as shown in figure

DWORD winapi asyncronousthread (

Lpvoid lpparameter // thread data
)

{

.....

}

(2) Use the createthtread function in the funcc function to create the function in (1) into a thread,Then directly return.

Void funcc (void)

{

.....

Createthread (..., asyncronousthread ,...);

Return;

}

Of course, there are many methods to write an asynchronous function, but the essence is not changed, that is, it must be implemented based on multithreading.

 

4. Callback and asynchronous mechanism

A callback function is a function provided by an application to a Windows system DLL or called by another DLL. It is generally used to intercept messages, obtain system information, or process asynchronous events. The application tells the DLL the address pointer of the callback function, and the DLL will call the function when appropriate. The callback function must comply with the pre-defined parameter format and transfer method. Otherwise, when the DLL is called, the program or system will crash. Generally, the callback function uses the standard windowsapi call method, namely _ stdcall. Of course, the DLL compiler can customize the call method, but the client program must follow the same rules. In the _ stdcall mode, function parameters are pushed to the stack in the order from right to left. Except for specifying a pointer or reference, parameters are passed by value, before the function is returned, the parameter is automatically popped up from the stack.

When a program calls a function (usually an API), it is equivalent to a program (Program) call. A function relationship is expressed as follows:
Call)
Program -------------------- → DLL

When a program calls a function, it passes its function address as a parameter to the function called by the Program (so this function is called a callback function ). the DLL functions that require callback functions are usually functions that must be executed repeatedly. the link is as follows:

Call)
Program -------------------- → DLL
Zookeeper
_______________________________ _______
Callback (callback)

When the function you call is passing the return value to the callback function, you can use the callback function to process or complete certain operations. How to define your own callback functions depends on the specific API functions used. many different types of callback functions have various parameters, the descriptions of these parameters generally include the callback function parameters and return values. in fact, the callback function is called by the DLL after the function you write meets certain conditions!

Windows also contains another broader callback mechanism, namely, message mechanism. Message is a basic control method of windows and a disguised function call. The purpose of sending a message is to notify the recipient to run a pre-prepared code, which is equivalent to calling a function. The wparam and lparam parameters attached to messages are equivalent to the function parameters. Applications can actively send messages. In more cases, they are waiting for Windows to send messages. Once a message enters the message queue, you can check the messages you are interested in and jump to execute the corresponding message processing code. The operating system serves applications and is called by applications. Once the application is started, it will wait for the operating system to call. This is also a callback, or a generalized callback. In fact, such callbacks can also be formed between applications. Assume that the Process
B receives a message from process a, starts a piece of code, and sends a message to process a, which forms a callback. This kind of callback is relatively concealed, which may lead to recursive calls. If the termination condition is missing, it will loop until the program is broken down. Messages can also form narrow callbacks. Replace the callback function address with the window handle. In this way, when the data size is relatively large, instead of calling the callback function, the API function sendmessage is used to send messages to the specified window. The recipient is responsible for comparing the data size and passing the comparison result to the sender through the return value of the message itself. The implemented functions are no different from the callback functions. Of course, in this example, the message is purely a snake, but the program is very slow. However, this is not always the case in other cases. In particular, sending messages is a good option when asynchronous calls are required. If the callback function contains low-speed processing such as file processing and the caller is not allowed, you need to change the synchronous call to asynchronous call to start a separate thread and then immediately execute the subsequent code, other things let the thread do it slowly. One alternative is to borrow
The API function postmessage sends an asynchronous message and immediately executes the subsequent code. This is much easier and safer than self-built threads.

Callback is used for inter-layer collaboration. The upper layer installs the function at the lower layer, which is the callback. The lower layer triggers the callback under certain conditions. For example, as a driver, it is an underlying layer, when he receives a data, in addition to processing the data at the current layer, he will also perform a callback to send the data to the upper application layer for further processing, which is common in hierarchical data communication. In fact, the callback API is very similar, and their commonalities are cross-layer called functions. However, the difference is that the API is provided to the upper layer for calling. Generally, this function is known to the upper layer; Callback is the opposite. It is a call provided by the top to the bottom layer. It is unknown to the lower layer and must be performed by the top layer.InstallThis installation function is actuallyAPIS provided at the lower layerAfter installation, the lower layer does not know the name of the callback, But itUse a function pointer to save the callback.To call the function, you only need to reference this function pointer and the related parameter pointer.
In fact, the callback function is written in the upper layer. The lower layer stores the function through a function pointer. When an event is triggered, the lower layer calls the upper layer function through the function pointer.

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.