gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:12:27 25 4
gpt4 key购买 nike

我有一个带有两个内部对象指针的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com