【问题标题】:Why is my worker working in a wrong thread?为什么我的工人在错误的线程中工作?
【发布时间】:2020-11-25 16:22:19
【问题描述】:

我有一个类 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 在一些不同的线程中工作,而不是我想要的。我做错了什么?

【问题讨论】:

    标签: c++ qt qthread


    【解决方案1】:

    它正在做它应该做的事情。术语stdin_receiver_thread_.get()-&gt;thread(); 产生QThread,其中stdin_receiver_thread_ 作为QObject 存在。换句话说,您的主线程或构造 Messenger 的任何地方。

    如果你只是写了:

    qDebug() << "stdin_receiver_thread_:" << stdin_receiver_thread_.get();
    

    你会得到预期的输出。


    std::unique_ptr<QThread>
    

    您不应该将std::unique_ptr 与您称为deleteLater()QObject 一起使用。这不可避免地会导致双重释放/堆损坏。

    【讨论】:

    • 哈,答案真快。谢谢你。我最近在做 JS 并且沉迷于链接调用并且不假思索地写了这个。再次感谢您如此快速而简短的回答。
    • 我应该只使用原始指针吗?还是从 deleteLater 辞职?
    • 是的,原始指针可能只是工作。或者当 QObject 被销毁时释放自己的 QT 智能指针。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-20
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多