Hi
I needed a way to use global variables in multiple threads without coding the thread safe stuff for every variable. The performance is not an issue because they will be accessed every now and then. I came up with the code below. I wonder if there is already a better (Qt) way of doing this. Thank you.
class QSafeString
{
private:
QMutex mMutex;
QString mVar;
public:
QSafeString(const QString& pValue = QString())
{
set(pValue);
}
void set(const QString& pValue)
{
mMutex.lock();
mVar = pValue;
mMutex.unlock();
}
QString get()
{
mMutex.lock();
return mVar;
mMutex.unlock();
}
};
class QSafeInt
{
private:
QMutex mMutex;
int mVar;
public:
QSafeInt(const int& pValue = 0)
{
set(pValue);
}
void set(const int& pValue)
{
mMutex.lock();
mVar = pValue;
mMutex.unlock();
}
int get()
{
mMutex.lock();
return mVar;
mMutex.unlock();
}
};
Usage:
// Main Thread:
QSafeString globalSafeString;
// Thread 1:
globalSafeString.set("value");
// Thread 2:
globalSafeString.set("value");
// Thread 3:
QString str = globalSafeString.get();
↧