我的主类是我的主窗口类,目前,几乎所有的操作都在其中执行,所有相关的变量都在定义中。为了提高速度,我想把一些计算外包给一个异步的、永久的线程(从QObject派生的工作者类移动到一个线程)。
一些变量(例如,包含OpenCV VideoCapture设备的QList )在这两个类中都使用了,但在worker类中使用得更多。
我在哪里声明这些变量?在主类中传递一个对worker类的引用,还是以其他方式传递?
发布于 2018-02-23 04:16:32
对不起,我的英语不好。
您可以在线程之间共享一些数据,但您必须保护不同线程对这些数据的访问-看看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
}https://stackoverflow.com/questions/48928790
复制相似问题