aladin8848 aladin8848 - 1 month ago 8
C++ Question

moveToThread() and than start() works with not constructed object?

I have something like this:


main.cpp


int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
static Communication *c = new Communication();
return a.exec();
}



communication.cpp


t is Qthread object...

Communication::Communication()
{
client = new EchoClient(QUrl(QStringLiteral("ws://localhost:1234")), 0);
client->moveToThread(&t);
connect(&t, SIGNAL(started()), client, SLOT(proces()));
t.start(QThread::HighestPriority);
}


How is it possible that when I call constructor, that object is not created yet but will be in next iteration of main loop? I am trying to achieve that firstly, object will be created and than moved to thread and will be paralely listenning to messages while waiting for user input.

Thx

EDIT

I just want to add client to another thread because in main thread I want to wait for user input like this if I enhance this a little bit

Communication::Communication()
{
client = new EchoClient(QUrl(QStringLiteral("ws://localhost:1234")), 0);
client->moveToThread(&t);
connect(&t, SIGNAL(started()), client, SLOT(proces()));
t.start(QThread::HighestPriority);


std::cout << "\n***************CLIENT MENU***************\n";
std::cout << "(1): SHOW
std::cout << "(2): EXIT\n";
std::cout << "***************************************************\n";

std::cin >> m_choice;

}


Problem is it will show menu and it will be blocked and not recieve any message

Answer

Console I/O is blocking: when cin >> m_choice is waiting for user input in the main thread, the main thread can't do anything else. The event loop won't run, no slots in the main thread will run, etc.

You may wish to move the console I/O based menu system to a dedicated thread, and interface it with the rest of the system via signals/slots.

Comments