Solved How to keep one class instance thread-safe in mutilthread with Qt?
-
@SpartaWHY117 Well, you need to protect all parts in your ProgramCore class where its member variables are modified and which can be executed in parallel from several threads. To do so you can protect those critical parts using QMutex and QMutexLocker.
For more details see: http://doc.qt.io/qt-5.9/qmutexlocker.html -
@jsulm how about change that core class into singleton? when use the method need to get the static instance
-
@SpartaWHY117 You can use singleton if you like, but it is not really a good pattern.
You need to serialize part of the getter:MySingleton* MySingleton::getInstance() { { QMutexLocker locker(mutex); if (instance == nullptr) instance = new MySingleton(); } return instance; }
-
@jsulm why use singleton is not a good pattern? actually in my project, the core class has many members, if lock every variables will be much troublesome.
-
-
@SpartaWHY117 said in How to keep one class instance thread-safe in mutilthread with Qt?:
@jsulm why use singleton is not a good pattern? actually in my project, the core class has many members, if lock every variables will be much troublesome.
Make your variables global then, what's the difference between a singleton and that ...? At least that way it looks and feels like C, while the singleton gives you a fake "object-oriented vibe". It's just plain C - a global variable with global functions.
-
@kshegunov
for my current project, I create an core instance in main thread. And the in both another two threads , i also create instances . So , is that means every thread has it's own instance and data? -
@SpartaWHY117 said in How to keep one class instance thread-safe in mutilthread with Qt?:
So , is that means every thread has it's own instance and data?
Yes, it's called reentrancy. You should try to ensure every thread works on its own data if possible.
-
@kshegunov actually i want to two threads to own the same instance which created in main thread. So i change the instance into QSharedPointer .
-
It's not that simple. If data is shared between threads, you have to synchronize them manually through a mutex or a semaphore.
QSharedPointer
as the name suggests, is a pointer that's being shared, not the object it points to.