我是在QT5.10中的主类或永久线程中声明某些变量

Do I declare certain variables in the main class or in a permanent thread in Qt5.10

本文关键字:线程 声明 变量 QT5      更新时间:2023-10-16

我的主要类是我的主窗口类别,目前,几乎所有操作都已执行,并且正在定义所有相关变量。为了提高速度,我想在异步的永久线程中外包某些计算(从qobject派生到线程的工作类别(。

在两个类中都使用了某些变量(例如包含OpenCV视频关注设备的QLIST(,但在工作类中更为大。

我在哪里声明这些变量?在主要班级中,并传递对工人班级或其他方式的参考?

对不起我的英语。

您可以在线程之间共享一些数据,但是您必须从不同的线程中保护对此数据的访问 - 查看qmutex,qreadWritelock。

坏示例:

#include <QList>
#include <QReadWriteLock>
template< typename T >
class ThreadSafeList{
Q_DISABLE_COPY(ThreadSafeList)
public:
    ThreadSafeList():
        m_lock{},
        m_list{}
    {}
    virtual ~ThreadSafeList(){}
    const QList<T>& lockForRead() const{
        m_lock.lockForRead();
        return m_list;
    }
    QList<T>& lockForWrite(){
        m_lock.lockForWrite();
        return m_list;
    }
    //don't forget call this method after lockForRead()/lockForWrite()
    //and don't use reference to m_list after call unlock
    void unlock(){
        m_lock.unlock();
    }
private:
    mutable QReadWriteLock m_lock;
    QList<T> m_list;
};

如果您尝试使用此类可能会遇到麻烦:

QString read(ThreadSafeList<QString>* list){
    // if list is empty, we got exception,
    // and then leave list in locked state
    // because unlock() don't called
    QString ret = list->lockForRead().first();
    list->unlock();
    return ret;
}
void write(ThreadSafeList<QString>* list, const QString& s){
    list->lockForWrite().append(s);
    //here we forget call unlock
    //and leave list in locked state
}