Reputation: 163
Let me just give you an example.
class B : public QThread {
public:
void run() {
}
};
class A : public QThread {
public:
void run() {
b1.start(); b2.start();
}
protected:
B b1, b2;
};
I want A::b1 and A::b2 to run as completely independent threads, not sharing resources of parent thread (A). Is there any way to specify main thread as parent thread of b1 and b2?
I've also looked at QThreadPool and QRunnable, and i don't understand, how is it possible to manage all runnables (for example, stop one of them, and then run it again) of threadpool.
Upvotes: 3
Views: 1507
Reputation: 12331
Subclassing QThread
is the wrong way of creating threads in Qt. QObject
provides the function moveToThread
which simply allows you to change the thread affinity of an object and its children.
Changes the thread affinity for this object and its children. The object cannot be moved if it has a parent. Event processing will continue in the targetThread.
To move an object to the main thread, use QApplication::instance() to retrieve a pointer to the current application, and then use QApplication::thread() to retrieve the thread in which the application lives.
So what you should do is to is to inherit from QObject
instead of QThread
and change your run function to move the B objects to other threads.
Sample Code (untested)
class B : public QObject {
Q_OBJECT
public:
void run() {
}
};
class A : public QObject {
Q_OBJECT
public:
void run() {
b1Thread = new QThread;
b2Thread = new QThread;
b1.moveToThread(b1Thread);
b2.moveToThread(b2Thread);
b1.run();
b2.run();
}
protected:
B b1, b2;
private:
QThread* b1Thread, b2Thread; // Delete them in the destructor.
};
You could construct the threads in main.cpp
and pass them to the B
class as arguments.
Notice the following concerning moveToThread
this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread.
Upvotes: 5