0

I am new to Qt and i read an Article about Multithreading under QT. And it seems that the best approach of doing so is to create a class that derives from QThread and implements a run method. Under Objective-C and GCD you can use blocks(kind of function-pointers) you just have to pass them to a queue and thats it. I think it is weird to, everytime i want to swap something out to a different thread, create a new class for that specific task.

So my Question now is, is it possible to pass function pointers to something thread-handling like GCD under Objective-C in QT ?

Sebastian Boldt
  • 5,283
  • 9
  • 52
  • 64

2 Answers2

3

The best approach for Qt threading is NOT to derive from QThread. If you're doing that, read this about why you're doing it wrong.

Instead, create a QThread object and move your widget to that thread.

QThread pThread = new QThread(parentObject);
//Assuming we have a class based on QObject
myObject->moveToThread(pThread);  // move our object to the thread
pThread->start(); // start the thread

You can then use signals and slots to communicate with the thread and the object. By doing it this way, you can also move more than one object to the new thread and no longer have to create a new, inherited QThread object per class.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
1

Yes, you can use Qt Concurrent framework to run a function in a different thread. An example from docs:

extern void aFunctionWithArguments(int arg1, double arg2, const QString &string);

int integer = ...;
double floatingPoint = ...;
QString string = ...;

QFuture<void> future = QtConcurrent::run(aFunctionWithArguments, integer, floatingPoint, string);

http://qt-project.org/doc/qt-4.8/qtconcurrentrun.html

headsvk
  • 2,726
  • 1
  • 19
  • 23