Calling a function on an QObject subclass that doesn't live in the current thread
-
According to the documentation :
"If you are calling a function on an QObject subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your QObject subclass's internal data with a mutex; otherwise, you may experience crashes or other undesired behavior."
Consider the following class:// Created on stack in main() => thread affinity = main thread class Model : public QObject { Q_OBJECT public: int getValue() const { // will be called from both main thread and non main thread return m_value; }; public slots: void incrementValue() { // will be called from both main thread and non main thread m_value++; }; private: std::atomic<int> m_value = 0; }
What is the internal data of Model?
std::atomic<int> m_value clearly is internal data.
It is already atomic and should not need to be protected by a mutex?But what about the code generated by the Q_OBJECT macro?
Must I somehow synchronize access to data here as well? If so how? -
Hi,
In your class, there's nothing more to do.
As stated in the documentation, it's your internal data access that you must protect.
-
Hi,
In your class, there's nothing more to do.
As stated in the documentation, it's your internal data access that you must protect.