How to convert QT asynchronous functions into synchronous Functions
(17:29:13)
Reprinted token
Tags:Eventloop Synchronous Functions Asynchronous Functions Qt It |
Category: C and CPP |
In QT, asynchronous functions are generally recommended. In addition to the non-blocking feature of asynchronous functions, the signal/slot feature of QT can be fully utilized in asynchronous functions. Therefore, in QT, many APIs are designed to use non-blocking asynchronous functions as APIS, and then the execution results are returned using signal. The user executes the API and uses the slot function to receive feedback results.
However, in many scenarios, we may need to synchronize functions. That is to say, the function must be blocked before the execution result is returned, and the corresponding execution result must be obtained after the function is called. At this time, for a large number of QT programs using signal/slot, it is often necessary to convert an asynchronous function into a synchronous function. The specific conversion method is as follows. For example, an asynchronous login function: void login (const qstring & username, const qstring & password); Return Value: Signal notification: onloginstatuschanged ();
The following is the synchronous version of this asynchronous function: int loginsync (const qstring & username, const qstring & password ){ Int timeout = 30*1000; // timeout value Qtimer T;
QEventLoop q;
t.setSingleShot(true);
Connect (& T, signal (timeout (), & Q, slot (quit ()));// Exit upon asynchronous call timeout
Connect (this, signal (onloginstatuschanged (), & Q, slot (quit ()));// Exit after asynchronous call is completed
Login (username, password ); // Call asynchronous Functions
t.start(timeout);
q.exec();
// You can perform further operations based on the returned results of the asynchronous function and return the function results.
} It should be noted that the processevent of eventloop actually encapsulates qiniacteventdispatcher. : Processevents. The QT help file contains the following description:
An event dispatcher es events from the window system and other sources. It then sends them to
Qcoreapplication Orqapplication Instance
For processing and delivery. qiniacteventdispatcher Provides fine-grained control over event delivery.
In other words, the existence of qcoreapplication or qapplication is required when qabstractevent or eventloop is used. This is not a problem for GUI programs. The problem is that for many consoleui command line programs, we often do not create qcoreapplication or qapplication objects. In such a scenario, eventloop cannot be used normally. Therefore, if a synchronous function encapsulated in this method is called in the command line, a qcoreapplicaion or qapplication object must exist.