I have one Reader and one Writer Thread. Reader reads from class member QVariant val and Writer writes into val. Now I want to do it in a synchronized manner. I implemented in this manner:
itm.h
#ifndef ITM_H
#define ITM_H
#include <QObject>
#include <QVariant>
#include <QMutex>
{
Q_OBJECT
public:
void setValue(const QVariant& newVal);
private:
};
#endif // ITM_H
}
#ifndef ITM_H
#define ITM_H
#include <QObject>
#include <QVariant>
#include <QMutex>
class Itm : public QObject
{
Q_OBJECT
public:
explicit Itm(QObject *parent = 0);
QMutex mutex;
void setValue(const QVariant& newVal);
QVariant getValue() ;
private:
QVariant val;
};
#endif // ITM_H
}
To copy to clipboard, switch view to plain text mode
and itm.cpp
#include "itm.h"
#include <QMutexLocker>
{
}
void Itm
::setValue(const QVariant &newVal
) {
val = newVal;
}
{
return val;
}
#include "itm.h"
#include <QMutexLocker>
Itm::Itm(QObject *parent) :
QObject(parent)
{
}
void Itm::setValue(const QVariant &newVal)
{
QMutexLocker locker(&mutex);
val = newVal;
}
QVariant Itm::getValue()
{
QMutexLocker locker(&mutex);
return val;
}
To copy to clipboard, switch view to plain text mode
Writer thread uses setValue() function and the reader getValue() function. Now the qt documentation says here that "If a function is not marked as thread-safe or reentrant, it should not be used from different threads. If a class is not marked as thread-safe or reentrant then a specific instance of that class should not be accessed from different threads." Now QVariant has not been marked as reentrant in the documentation. So does that mean that the above method I am trying to implement to achieve synchronization is ill-advised, and if used across threads, QVariants is NOT an option. Or I am misinterpreting??
Bookmarks