2

What is the correct way to use Singleton pattern with QObject which is gonna be used with multithreading? Of course this way should exclude all Qt multithreading errors like

QObject: Cannot create children for a parent that is in a different thread.

VP.
  • 15,509
  • 17
  • 91
  • 161

2 Answers2

0

I do not think that there is a generally accepted correct way to do this. The problem is that the Singleton pattern is avoided in modern software, because having a global reference to to a certain object makes unit testing really hard, sometimes impossible.

Do not misunderstand me, it is ok to have singletons where it seems logical. The problem is with the pattern, where you access them through a global variable or function like MySingletonClass::getInstance().

Try injecting it instead where it is needed through constructor parameter, or setter methods.

About multithreading: I do not think that Singletons are any special in this aspect. They are the same as any object accessed concurrently.

Étienne
  • 4,773
  • 2
  • 33
  • 58
Gábor Angyal
  • 2,225
  • 17
  • 27
  • One example - my singleton is network connection which is ought to be unique instance. I wanna use it concurrently to avoid gui freezes but I have error I wrote in the question. People on stackoverflow says "create object on heap and ..." but it is singleton, I can't create it on heap + it must be unique. – VP. Jan 17 '15 at 13:18
  • Thats ok. You can have it uniqe, no problem with that. You can surely create it on the heap, why couldn't you? Research the subject about singletons. Understand that having a singleton is different from using the singleton _pattern_. This may be a good starting point: [link](http://stackoverflow.com/questions/7267061/alternatives-to-singletons). – Gábor Angyal Jan 17 '15 at 13:25
0

The run-time error message is specific to Qt and not C++. Of course you can use the object created on the other thread every each way you want. BUT you cannot pass it as a parent (that is Qt) to objects created on another thread so that the parent cannot destroy its children while itself getting destructed. It is also has to do with Qt messaging mechanism and timers. You may find QObject::moveToThread description interesting as well.

Alexander V
  • 8,351
  • 4
  • 38
  • 47