c++ - 为什么我的 worker 在错误的线程中工作?

标签 c++ qt qthread

我有一个带有两个内部对象指针的Messenger类:

    std::unique_ptr<QThread> stdin_receiver_thread_ = nullptr;
    std::unique_ptr<ReceiverWorker> stdin_receiver_ = nullptr;
Messenger的构造函数中,我创建了这些对象并将其分配给这些智能指针,如下所示:
Messenger::Messenger(QObject *parent) : QObject(parent) {

    // create the objects
    stdin_receiver_thread_ = std::make_unique<QThread>(); 
    stdin_receiver_ = std::make_unique<ReceiverWorker>();
    //
    qDebug() << "stdin_receiver_thread_:" << stdin_receiver_thread_.get()->thread();

    // I assign the worker to this the newly created thread
    stdin_receiver_->moveToThread(stdin_receiver_thread_.get());
    //

    connect(stdin_receiver_thread_.get(), &QThread::started, stdin_receiver_.get(), &ReceiverWorker::process);
    connect(stdin_receiver_.get(), &ReceiverWorker::receivedMessage, stdin_receiver_thread_.get(), &QThread::quit);
    connect(stdin_receiver_.get(), &ReceiverWorker::receivedMessage, stdin_receiver_.get(), &QObject::deleteLater);
    connect(stdin_receiver_thread_.get(), &QThread::finished, stdin_receiver_thread_.get(), &QObject::deleteLater);

    stdin_receiver_thread_->start();
}
在我的ReceiverWorker::process()里面
我打电话
qDebug() << "Receiverworker currentThread:" << QThread::currentThread();
现在,这两个qDebug()调用将输出不同的值:
stdin_receiver_thread_: QThread(0x20a24e57ba0)
Receiverworker currentThread: QThread(0x20a2e6f58e0)
因此,就像ReceiverWorker在与我想要的线程不同的线程中工作。我究竟做错了什么?

最佳答案

它正在做应该做的事情。术语stdin_receiver_thread_.get()->thread();产生QThread,其中stdin_receiver_thread_作为QObject存在。换句话说,您的主线程或Messenger的构建位置。
如果您只是写了:

qDebug() << "stdin_receiver_thread_:" << stdin_receiver_thread_.get();
您将获得预期的输出。
std::unique_ptr<QThread>
您不应将std::unique_ptr与称为QObjectdeleteLater()一起使用。不可避免地导致双重释放/堆破坏。

关于c++ - 为什么我的 worker 在错误的线程中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63266065/

相关文章:

c++ - Qt 5 禁用单击并按住

python - PySide2 Qthread 崩溃

python - 将数据传递到 Python GUI 中的 QThread

c++ - QAction : No such file or directory

c++ - 将 bool 转换为 QString

c++ - 实现我自己的 myless

c++ - opencv 3.0 findContours 函数在窗口中不起作用

c++ - QTimer 不按建议的时间间隔发出信号

c++ - Qt 和 C++ 在没有科学记数法的情况下显示来自 MySQL 的大 DECIMAL 数

multithreading - 为什么从主线程调用插槽?