Qt Console Application: while loop blocks event loop
Im making a console application where Im getting user input with std::getline() (in a while loop). Im also using QextSerialPort (inherits QIODevice). Thus I need an event loop so I'm using QCoreApplication and calling a.exec().
The problem is getline() blocks event loop and, while it's blocked, I can't receive anything from serial port. I tried to use
QCoreApplication::processEvents() in the while(1){getline()} loop, but found that's not a good solution. Then, I tried to call
QCoreApplication::processEvents() in a QThread but it didn't work.
Here's the code Im using:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Base *base = new Base();
Commander *commander = new Commander(base);
QObject::connec开发者_JAVA技巧t(commander, SIGNAL(end()), &a, SLOT(quit()));
QTimer::singleShot(0, commander, SLOT(run()));
return a.exec();
}
void Commander::askToConnect()
{
if(base->connect() == false){
cout << "Failed to open port." << endl;
}
}
void Commander::run{
string inputline;
askToConnect();
while(1){
QCoreApplication::processEvents(); // ???
cout << endl << "> ";
getline(cin, inputline);
// ...
}
}
How can I have a getline() (or similar method) without blocking event loop?
Yes, i got similar experiences with the ProcessEvent() method called from the main thread. The problem is that it's just put on top of the current call stack and that can have other nasty side effects like endless calling depth or re-entrance problems.
I would just add a few threads to your application to create a clean solution. Since getLine() belongs to the (console) user interface, I would keep it in the main thread and move the networking code into an extra thread but other solutions are also possible (spawning threads for all kinds of interactions and just maintaining them from the main thread).
精彩评论