我是在QT5.10中的主类或永久线程中声明某些变量
Do I declare certain variables in the main class or in a permanent thread in Qt5.10
我的主要类是我的主窗口类别,目前,几乎所有操作都已执行,并且正在定义所有相关变量。为了提高速度,我想在异步的永久线程中外包某些计算(从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
}
相关文章:
- 如何声明由多个线程调用的 C++ DLL 的内部类,而无需导出类
- 如果在 2 个线程中使用,是否值得将size_t声明为 std::atomic?
- 当线程处理不同的类时,应该在哪里声明条件变量、互斥对象
- 线程函数参数的前向声明不起作用
- 在向量上声明缩减,在 1 个线程上运行给出的结果与没有 openmp 的结果不同
- 我是在QT5.10中的主类或永久线程中声明某些变量
- Windows 线程池,'PTP_CALLBACK_INSTANCE':未声明的标识符
- 是否可以在全球范围内声明一个提升线程
- 如何匿名声明std::线程
- 在C++中将成员函数的线程声明为类的成员
- 线程之间共享的变量的声明
- 将函数放在类中,然后声明"New"是否使其线程安全?
- 通过引用将循环计数器或范围声明传递给线程有什么区别
- C++错误中的简单线程 - 尚未声明'Lib'
- 全局变量外部声明后的线程专用指令
- Xcode 线程信号错误和本地声明错误
- 在运行循环外声明、分配和释放线程局部指针变量
- 错误:无法从另一个线程启动计时器.使用未声明计时器的QFuture
- 将一个函数声明为transaction_safe就足够了吗?这样它们就可以线程安全地使用了
- 线程变量的声明和影响