Hi,
I need to have access to several information from different threads so I made a class like this:
class Foo
{
public:
void increase()
{
m_ints << 42;
}
private:
QVector<int> m_ints;
};
class Foo
{
public:
void increase()
{
QWriteLocker l(&m_lock);
m_ints << 42;
}
private:
QReadWriteLock m_lock;
QVector<int> m_ints;
};
To copy to clipboard, switch view to plain text mode
Foo is then instantiated in the main thread and a pointer is passed to the relevant threads. So far so good. Now I'd like to get informed if e.g. m_ints gets changed. So QObject came into play but as it is only reentrant (except connect and disconnect) it is getting complicated.
Let's think of this modified class:
{
public:
void increase()
{
m_ints << 42;
emit added(42);
}
signals:
void added(int);
private:
QVector<int> m_ints;
};
class Foo : public QObject
{
public:
Foo: QObject(0) {}
void increase()
{
QWriteLocker l(&m_lock);
m_ints << 42;
emit added(42);
}
signals:
void added(int);
private:
QReadWriteLock m_lock;
QVector<int> m_ints;
};
To copy to clipboard, switch view to plain text mode
So, Foo's thread affinity is my main thread.
- Is this class still thread-safe since it does not use any functions of QObject? What about emit?
- What does this mean for calling increase() through a pointer from a different tread. Which thread does the "work" (manipulating m_ints) of increase(): The main thread or the local thread?
If that solution is bad, what would be a good approach to get informed about changes? (Beside the caller of the function emits afterwards the changes ala
myFoo->increase();
emit mySignalAdded(42);
myFoo->increase();
emit mySignalAdded(42);
To copy to clipboard, switch view to plain text mode
Thanks
Lykurg
Bookmarks