moveToThread()和start()适用于未构造的对象

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

本文关键字:对象 适用于 start moveToThread      更新时间:2023-10-16

我有这样的东西:

main.cpp

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

communication.cpp

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);
}

怎么可能,当我调用构造函数,对象还没有创建,但将在主循环的下一次迭代?我正在努力实现这一点,首先,对象将被创建,然后移动到线程,并将并行地监听消息,同时等待用户输入。

Thx

编辑

我只是想把客户端添加到另一个线程中因为在主线程中,我想等待这样的用户输入如果我稍微增强一下

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): EXITn";
std::cout << "***************************************************n";
std::cin >> m_choice;
}

问题是它将显示菜单,它将被阻止,没有收到任何消息

控制台I/O阻塞:当cin >> m_choice在主线程中等待用户输入时,主线程不能做任何其他事情。事件循环不会运行,主线程中没有插槽会运行,等等。

您可能希望将基于控制台I/O的菜单系统移动到专用线程中,并通过信号/插槽将其与系统的其余部分连接。