将对象传递给多线程对象 Qt
Passing objects to multithreading objects Qt
我想知道将另一个对象传递给在 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(。
相关文章:
- 将对象传递给多线程对象 Qt
- 在 While 循环中重用对象的多线程
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- 修改多线程应用程序中的对象
- 在多线程环境中正确销毁对象
- 多线程可以访问同一weak_ptr对象C++吗?
- 对象析构函数在多线程处理时不断被调用,但该对象并未超出范围
- 关于多线程程序中的临时对象
- 在多线程环境中交换C 地图对象
- 在多线程中是否可能发生读取对象的一半大小?
- 通过引用和多线程传递对象
- 使用多线程处理对象数组 - 无效使用 void 表达式错误
- 如何为多线程应用程序创建全局对象
- C++11 使用共享对象的多线程处理
- 从多线程程序中安全地删除对象
- 我不明白多线程游戏中的对象不匹配
- 关闭MFC对话框时多线程对象被破坏
- 用于虚拟对象的Linux线程.有人能解释linux中多线程库之间的区别吗
- 控制对多线程程序中字符串对象的访问的最佳方法
- 多线程客户端中 COM 对象的初始化和实例化