为什么我的工作人员在错误的线程中工作?

Why is my worker working in a wrong thread?

我有一个 class 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 与您调用 deleteLater()QObject 一起使用。这不可避免地会导致 double-free / 堆损坏。

您正在 QThread 对象上调用 QObject::thread()。 docs 表示:“Returns 对象所在的线程。” QThread 是一个存在于主线程中的对象。我认为您的函数按预期工作,您只是没有比较 qDebugs 的正确值。