将对象传递给多线程对象 Qt

Passing objects to multithreading objects Qt

本文关键字:对象 多线程 Qt      更新时间:2023-10-16

我想知道将另一个对象传递给在 GUI 线程以外的另一个线程中运行的对象是否线程安全。 我的意思是,做这样的事情是线程安全的吗? 此示例对象在应用的整个生存期内发生了什么?

在 worker.h 文件中

private:
Example* example;

在 worker.c 文件中

Worker::Worker(QObject *parent, Example *example) :
QObject(parent),
example(example)
{
}

在主中

Example example(nullptr);
auto worker = new Worker(nullptr, &example);
auto thread = new QThread;
Printer printer;
QObject::connect(thread, &QThread::started, worker, &Worker::doWork);
QObject::connect(worker, &Worker::readedText, &printer, &Printer::printMessage);
QObject::connect(worker, &Worker::workDone, thread, &QThread::quit);
QObject::connect(thread, &QThread::finished, worker, &Worker::deleteLater);
worker->moveToThread(thread);
thread->start();

如果 GUI 线程必须使用 Example 对象,因为我将指针传递给该对象怎么办?

一般来说,将对象传递到不同的线程并没有错,只要您确保在读取/写入该对象时存在某种机制来处理并发问题即可。最简单的方法是通过使用条件变量/互斥锁,在使用对象时获取(锁定(对象。其他线程将等到锁不再使用,以便它们可以保留它。

您编写的代码不起作用。"example"是一个局部变量,当函数返回时将被删除。您需要确保变量的生存期始终超过其使用量。您可能希望线程持有指向动态分配对象的智能指针(如std::shared_ptr(。