The problem of QT asynchronous function and synchronous function exchange

Source: Internet
Author: User
Tags call back


synchronous functions and asynchronous functions


1. Based on Microsoft's MSDN commentary:



(1) synchronization function : When a function is executed synchronously, it is not returned immediately when the function is called, until everything that the function has done has been done.



(2) async function : If an asynchronous function is called, the function returns immediately although the operation task specified by the function is not yet complete.



(3) What are the effects of invoking each of these two functions in one thread on the calling thread?



When a thread invokes a synchronous function (for example, the function is used to complete a write file task), if the function does not immediately complete the specified action, the operation causes the calling thread to hang (handing over the CPU's use to the system, allowing the system to be used by other threads) until the operation specified by the synchronization function is complete before returning. Eventually, the calling thread will be re-dispatched.



When a thread invokes an asynchronous function (for example, the function is used to complete a write file task), the function returns immediately, even though its mandated tasks are not completed, so that the thread executes the next statement of the asynchronous function without being suspended. So how does the work of this asynchronous function be done? Of course it's done by another thread, so where does the new thread come from? It is possible that a newly created thread in an asynchronous function might also be a ready-made thread in the system.



(4) How does a thread that invokes an async function synchronize with the results of an asynchronous function?



To resolve this problem, the calling thread needs to use a " wait function " to determine when the asynchronous function completed the specified task. So the thread calls the Async function immediately after calling a "wait function" to suspend the calling thread until the asynchronous function finishes all its operations before executing the next instruction in the threads.



Have we found an interesting place?! Is that we can use the wait function to encapsulate an asynchronously executed function into a synchronous function.



2. Synchronous call and Asynchronous call



         Operating system has been developed to today is very ingenious, thread is one of the masterpieces. The operating system divides the CPU processing time into many short time slices, executes the instruction of a thread in time T1, and executes the instruction of the next line in time T2, the thread executes in turn, the result seems to be all threads are marching together. In this way, you can create multiple threads during programming, execute in the same period, and each thread can "parallelize" the different tasks.
         in single-threaded mode, The computer is a strictly von Neumann machine, when a code calls another piece of code, it can only take synchronous calls, and must wait for the code to finish executing the returned results before the caller can proceed. With multi-threaded support, you can take the asynchronous call, the caller and the callee can belong to two different threads, the caller initiates the thread of the call, and waits for the other party to return the result to continue executing the subsequent code. After the call has been executed, the caller is notified by some means: The result is already out, please do your discretion.


some processing in the computer is time consuming. Invoking this processing code can severely affect program performance if the caller is standing there waiting. For example, if you need to open a file to read the data in a program after startup, and then perform a series of initialization processing according to these data, the main window of the program will not be displayed, so that the user feels that the program is not going out for half a day, too bad. With asynchronous calls, the problem can be easily resolved by putting the entire initialization process into a single thread, and then going down the main thread and letting the primary window appear instantly. When the user stares at the window, the initialization process is done quietly behind the scenes. After the program starts to run stably, it can continue to use this technique to improve the instantaneous reaction of human-computer interaction. When the user clicks the mouse, the action that is fired if it is more time consuming, then click the mouse will not react immediately, the whole program appears very heavy. With the help of asynchronous call processing time-consuming operation, so that the main thread ready to wait for the next message, the user clicks the mouse feel easy and fast, will certainly be good for the software.
asynchronous calls are particularly effective for handling data that is entered externally. If a computer needs to request data from a low-speed device and then a lengthy data-processing process, it is obviously not advantageous to use synchronous invocation: The computer makes a request to an external device and then waits for data entry, and after the external device sends data to the computer, it waits for the computer to complete the processing before issuing the next data request. Both sides have a waiting period, stretching the entire process. In fact, the computer can issue the next data request before processing the data, and then immediately process the data. If the data processing is faster than data acquisition, the only computer to wait for, the external device can continuously and constantly collect data. If the computer connects multiple input devices at the same time, it can send data requests to each device in turn and handle the data sent by each device at any time, and the whole system can keep running at high speed. The key to programming is to attribute the data request code and the processing code to two different threads respectively. The data processing code calls an asynchronous function that requests an information and then handles the data at hand. After the next set of data arrives, the data processing thread receives a notification, ends the wait state, issues the next data request, and then resumes processing the data.
When the call is made asynchronously, the caller turns away without waiting for the caller to return the result, so there must be a mechanism to notify the caller when the callee has the result. In the same process there are many ways to use, the author commonly used by the callback, event object and message.
Callback:
The callback method is simple: when an asynchronous function is called, a function address is placed in the parameter, the asynchronous function holds the address, and the callback function can be notified to the caller after the result is given. If you wrap an asynchronous function into an object, you can replace the callback function address with an event and send a notification to the caller through the event-handling routine.
Event : event is a common synchronization object provided by Windows systems to align the steps between different threads in asynchronous processing. If the caller has nothing to do for the time being, you can call the wait function there, and the event is in the nonsignaled state. When the event object is placed in the signaled state after the call is made, the wait function automatically finishes waiting, causing the caller to re-act and remove the processing result from the callee. This way is more complicated than the callback method, the speed is relatively slow, but there is a great deal of flexibility, can be a lot of tricks to adapt to the more complex processing system.   

message: sending notifications with Windows messaging is a good choice, simple and secure. A user message is defined in the program and the message-handling routine is prepared by the caller. This message is sent to the caller immediately after the result of the call, and the results are passed through both the WParam and LParam parameters. The message is always associated with the window handle, so the caller must use a window to receive the message, which is inconvenient. In addition, the speed is affected by the message contact, and the callback method is more advantageous when high-speed processing is required.
if the caller and the callee belong to two different processes, due to the gap in memory space, it is generally easier and more reliable to use Windows message sending notification, the callee can transmit data to the caller by the message itself. The event object can also be shared among different processes by name, but can only be notified, itself cannot transmit data, need to use the memory sharing means such as Windows message and filemapping or with the aid of communication means such as mailslot and Pipe.
The principle of asynchronous invocation is not complicated, but the actual use of the problem is easy to be confused, especially when different threads share code or share data prone to problems, programming need to always pay attention to the existence of such a share, and through a variety of status flags to avoid conflicts. The mutex objects provided by Windows systems are particularly handy here. A mutex can have only one jurisdiction at a time. Once a thread has given up jurisdiction, another line can take over. When a thread executes into a sensitive zone, it takes over the mutex, causes the other threads to block behind the wait function, discards the jurisdiction immediately after leaving the sensitive area, and the wait function ends waiting for the other thread to visit the sensitive area. This can effectively prevent multiple threads from entering the same sensitive zone.
because asynchronous calls are prone to problems, designing a secure and efficient programming scenario requires a lot of design experience, so it's best not to misuse asynchronous calls. Synchronous invocation is more comfortable after all: no matter where the program goes, as long as the dead stare at the mobile point can know, not like the asynchronous call, there is always a siege, uneasy feeling. you can even convert an asynchronous function to a synchronous function if necessary. The method is simple: Call the wait function immediately after calling the async function, and so on, and wait for the async function to return the result before continuing to go down.


If the callback function contains low-speed processing such as file processing, the caller can not, need to change the synchronous call to an asynchronous call, to start a separate thread, and then immediately execute the subsequent code, the rest of the matter let the thread to do. An alternative is to use the API function PostMessage to send an asynchronous message and execute the subsequent code immediately. It's a lot easier and safer than having a thread of your own.






If your server side of the number of clients, your server is asynchronous, but your client can be used in sync, the client general function is relatively single, received data to perform the following work, so get synchronized in that and so on.



First, give an example of a call:



block block means that you dial someone's phone, but the person is not there, so you hold the phone and wait for him to return, no longer use the phone. synchronization is about the same as blocking.



non-blocking nonblock means that you dial someone's phone, but the person is not there, so you hang up and call back later. As for the time he came back no, only call to know. The so-called "polling/poll".



Async means that you dial someone's phone, but the person is not there, so you ask the person who answered the phone to tell that person (leave a message) and call you back when you get home.



Second, synchronous asynchronous and blocking and non-blocking are two different concepts.



Synchronous asynchronous refers to the mode of communication, while blocking and non-blocking refers to whether to wait for the action to complete before returning when receiving and sending



The first is the synchronization of the communication, mainly refers to the client after sending the request, it must be on the server after the response to send the next request. so all requests at this time will be synchronized on the server.



Next is the asynchronous communication, refers to the client after sending the request, do not have to wait for the service side of the response to send the next request, so for all the request action will be asynchronous on the server, the request link is like a request queue, all the actions will not be synchronized here.



Blocking and non-blocking are only applied in the requested read and send.



In the implementation process, if the server is asynchronous, the client is also asynchronous, the communication efficiency will be very high, but if the server is returned to the requested link, the client can be synchronized, in this case, the server is compatible with synchronous and asynchronous. Conversely, there is no problem if the client is asynchronous and the server is synchronous, but the processing is inefficient.






Imagine that you are a physical education teacher who needs to test 400 meters of 100 students. You certainly will not let 100 students start together, because when the students return to the end, you have no time to record the results of the students.



If you get a classmate to start every time and wait for him to return to the finish line, let the next one run until all the students have finished. Congratulations, you have mastered the synchronous blocking mode. You have designed a function that passes in the student number and start time, and the return value is the time to reach the end. You can call this function 100 times to complete the test task. This function is synchronous because you can get the result as long as you invoke it, and this function is also blocked, because once you call it, you have to wait until it gives you results and you can't do anything else.



If you let one of your classmates start every 10 seconds, until all the students are out of the way, and every student on the other side goes back to the finish record, until all the students have run. Congratulations, you've mastered asynchronous nonblocking mode. You have designed two functions, one of which records the start time and student number, the function you will call 100 times, another function to record the arrival time and student number, the function is an event-driven callback function, when a classmate arrives at the end, you will be passive call. The function you invoke is asynchronous because you call it and it does not tell you the result; This function is also non-blocking, because once you invoke it, it returns immediately, and you can call it again without waiting. But just call this function 100 times, you do not complete your test task, you also need to passively wait to call another function 100 times.



Of course, you will soon realize that the efficiency of synchronous blocking mode is significantly lower than asynchronous nonblocking mode. So, who else uses synchronous blocking mode? Yes, the asynchronous mode is more efficient, but more troublesome, you have to record the start of the classmate's data, while the data to the students to record, and the students return to the end of the order and the start of the order is not the same, so you have to keep on your score book to find the student number. You tend to pigtailed in the midst of bustle. You might come up with a smarter way: You take a lot of stopwatch and let the classmates test each other in groups. Congratulations to you! You have mastered the multi-threaded synchronization mode!



Each classmate with a stopwatch can call your sync function independently, so that it is not error-prone, efficiency is greatly improved, as long as the stopwatch enough, synchronization efficiency can reach or even more than asynchronous.



Understandably, your question may be: Since multithreaded synchronization is fast and good, is there any need for asynchronous mode?



Unfortunately, asynchronous mode is still very important, because in many cases you can't get a lot of stopwatch. The peer-to-peer system you need to communicate with may only allow you to create a socket connection, as many large business systems in the financial and telecommunications industries require.



First, synchronous blocking mode



In this pattern, the user-space application executes a system call and blocks until the system call is complete (data transfer complete or error occurs).



Second, synchronous non-blocking mode
A slightly less efficient way to synchronize blocking I/O. The non-blocking implementation is that the I/O command may not be immediately satisfied, requiring the application to call many times to wait for the operation to complete. This can be inefficient, because in many cases, when the kernel executes this command, the application must be busy waiting until the data is available, or trying to perform other work. Because the data becomes available in the kernel and there is a certain interval between the user's call to the read return data, this results in a decrease in overall data throughput. However, asynchronous non-blocking is more efficient because it is multi-threaded.






/ * create the connection by socket
* means that connect "sockfd" to "server_addr"
* Synchronous blocking mode
* / if (connect (sockfd, (struct sockaddr *) & server_addr, sizeof (struct sockaddr)) == -1)
{
perror ("connect");
exit (1);
) / * Synchronous non-blocking mode * / while (send (sockfd, snd_buf, sizeof (snd_buf), MSG_DONTWAIT) == -1)
{
sleep (1);
printf ("sleep \ n");
} 







Network Program development process:



1. Demand Analysis



2. According to the requirements of the packet design (generally divided into Baotou and packet data two parts, Baotou used to store packets of necessary information, such as information type, data length, etc.)



3. Define the transport protocol (how to transfer).



4. Understand the requirements, design the overall architecture, use design patterns and other methods to conduct problem analysis and design class diagrams.



5. Implementation, usually with multithreading to achieve communication problems. (There are typically waiting for a client to request a thread, receive a data thread, send a data thread, resource cleanup thread).



6. Implement the server side.



7. Implement the client.






The problem of QT asynchronous function and synchronous function exchange


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.