Give me recomendations for use Qthread
-
Hello i am asking for advice to use Qthread. I have the need to use because i am developing a software that receives a package of stream data audio and video (file.TS) form an usb device , one part of my code have to mange the buffer, other part have to change the frequency of the device, and other paret have to play the video.
I have a class called "backend" this class is just for do the operation with the usb, transfers and configurations, it doesn't have any qobject or qwidget or any ui element just back end, no pointers or connections to gui elements, just pure code.
In backend class, i have a part of the code that set the frequency and also do the communication with the usb --> this i would like to put it in a thread.
For example in the window.iu i have a signal.
void MainWindow::on_pushButton_clicked()
{
//intialize turner and demulator
one.initialize_tuner_demulator();
//Tune the 521000 frequency
one.tune_in(521000);
}
The usb device already response and set the frequency with this code, it works, "one" is a object of backend class and the other are functions are of backend class.I would like a thread that always be looking if this button was pressed, i don't want the main thread keep a eye in this button. This button just were used to this task only change frequency
I have the doubt if i must declare a new thread class or make a thread in the mainwindow class.
-
@aurquiel Hmmm. OK. I'll try and help.I laugh at anyone who calls themselves an expert in threading/parallelism!!!
So, the part that receives from the USB device (your "backend" class). Define a variety of slots on that object, these will be your triggers and event handlers. This must be a QObject. The reason is that you can now use Qt's event buffering mechanisms which are ideal for splitting work into parallel chunks. One of these slots will be something like "go". Start the "go" like this.
//Create an instance of the backend/worker worker = new Worker(); // Now create a thread and move the backend object to it worker->moveToThread(&thread); // Send the worker/backend thread a message (invoke "go") QMetaObject::invokeMethod(worker, "go", Qt::QueuedConnection); // Start the thread, this starts the event loop and the "go" method will be invoked thread.start();
This thread can communicate with other threads (and vice versa) using queued connections. The object (worker/backend) will receive events in the thread context to which it has been moved.
Many objects (esp QObjects and byte arrays/strings) are passed /very/ quickly through queued connections due to copy on write and reference counting semantics.
So, maybe you have several interconnected processes here. There's the backend, the GUI and the video player. It may well be that, for sanities sake, the GUI and the video player are one in the same thread, especially if they are in the same window.
Threads communicate via "emit"s and you just have to connect up the signals and slots between threads.
You could derive from QThread and implement 'run' and I have done this but the advantages of using the signal/slots and event loops far outweigh the very small amount of additional start up code.
Does this help?
-
@matthew.kuiash said in Give me recomendations for use Qthread:
OK. I'll try and help.I laugh at anyone who calls themselves an expert in threading/parallelism!!!
Oh, but thank you very much ... isn't my face red now ... ;)
A good answer by the way. One note I'd like to add here about this statement:You could derive from QThread and implement 'run' and I have done this but the advantages of using the signal/slots and event loops far outweigh the very small amount of additional start up code.
While a rule of thumb is to prefer worker objects in certain cases where processing throughput is critical reimplementing
QThread::run
is the way to go. This, additionally, doesn't exclude having signals raised from therun()
implementation, the implication is only that you can't have queued signal-slot connections executed in the context of that particular thread (direct connections still work fine). -
@kshegunov said in Give me recomendations for use Qthread:
the implication is only that you can't have queued signal-slot connections executed in the context of that particular thread (direct connections still work fine).
OK, maybe there are a few experts!
The above statement. I assume you mean by "context" you mean the thread running the "run" function.
Why is that? Is it simple because "exec" is not being invoked inside run therefore the event loop isn't running and queued events will never be invoked? Do the direct connections work because they are executed in the thread context of the caller/emitter?
-
@matthew.kuiash said in Give me recomendations for use Qthread:
The above statement. I assume you mean by "context" you mean the thread running the "run" function.
Yes,
QThread::run
is the function that's the root of the thread context (the root of the thread stack) in Qt.Why is that? Is it simple because "exec" is not being invoked inside run therefore the event loop isn't running and queued events will never be invoked?
Yes again!
Do the direct connections work because they are executed in the thread context of the caller/emitter?
And, yes yet again!
-
@kshegunov said in Give me recomendations for use Qthread:
Do the direct connections work because they are executed in the thread context of the caller/emitter?
And, yes yet again!
Yup, now I remember why I went for (and liked) the worker thread/QObject approach in my audio sequencer and my resource packer. It was to avoid hand synchronising everything with mutexes/critical sections etc.
Thanks.
-
@matthew.kuiash said in Give me recomendations for use Qthread:
Yup, now I remember why I went for (and liked) the worker thread/QObject approach in my audio sequencer and my resource packer. It was to avoid hand synchronising everything with mutexes/critical sections etc.
Understandable. Although, approaches can also be mixed. E.g. the other way around - having queued slot call in a thread with a worker object, but the signal which triggers it to be raised from a thread that doesn't have an event loop (i. e. one that has
QThread::run
reimplemented). Something along those lines:class ThreadSubclass : public QThread { Q_OBJECT signals: void somethingInteresting(); protected: void run() Q_DECL_OVERRIDE { emit somethingInteresting(); } }; class Worker : public QObject { Q_OBJECT public slots: void handleInteresting() { // We are in workerWithObject (see below for what this means) } };
And one can hook it up like this:
int main() { QThread workerWithObject; workerWithObject.start(); Worker * workerObject = new Worker; workerObject->moveToThread(&workerWithObject); QObject::connect(&workerWithObject, &QThread::finished, workerObject, &QObject::deleteLater); ThreadSubclass workerWithRun; QObject::connect(&workerWithRun, &ThreadSubclass::somethingInteresting, workerObject, &Worker::handleInteresting); workerWithRun.start(); return 0; }
-
Well i was looking how to code, i can make it work. But i have some warnings
I have some buttons to change the frequency of a tuner of TDA (Digital Television) that instruction goes through usb control transfer connection using libusb that part works. All that functions are in the backend class.
Do some changes in backend class add the macro QObject
#ifndef BACKEND_H #define BACKEND_H #include <libusb-1.0/libusb.h> //Include libsub #include <QObject> class backend: public QObject { Q_OBJECT .. ... .....
In the MainWIndow
//Create a global object to backend class backend *usb_and_channels=new backend; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { //This create the ui interface of QT ui->setupUi(this); //Star thread one QThread *thread_one = new QThread; //Moving channels object to thread_one usb_and_channels->moveToThread(thread_one); //Connecting thread_one started signal with usb initilization Begin connect(thread_one,SIGNAL(started()),this,SLOT(usb_connecting_and_status())); //Connecting thread_one started signal with usb initilization End //Connecting thread_one started signal with channels buttons cliked Begin connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_2->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_3->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_4->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_5->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_6->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_7->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_8->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_9->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_10->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_11->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_12->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_13->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_14->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_15->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_16->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_17->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_18->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_19->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_20->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_21->clicked();)); connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_22->clicked();)); //Connectic thread_one started signal with channels buttons cliked Begin //Sarting thread one signal emited thread_one->start(); }
In the buttons For example one channel
//Channel 123TV void MainWindow::on_pushButton_2_clicked() { //Initilize turnner and demulator usb_and_channels->initialize_tuner_demulator(); //Tune frequency usb_and_channels->tune_in(521000); }
When i compile i don't have warnings but after run i got this ones
QObject::connect: No such slot QPushButton::ui->pushButton->clicked(); in ../PIZZA/mainwindow.cpp:29 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_2->clicked(); in ../PIZZA/mainwindow.cpp:30 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_3->clicked(); in ../PIZZA/mainwindow.cpp:31 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_4->clicked(); in ../PIZZA/mainwindow.cpp:32 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_5->clicked(); in ../PIZZA/mainwindow.cpp:33 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_6->clicked(); in ../PIZZA/mainwindow.cpp:34 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_7->clicked(); in ../PIZZA/mainwindow.cpp:35 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_8->clicked(); in ../PIZZA/mainwindow.cpp:36 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_9->clicked(); in ../PIZZA/mainwindow.cpp:37 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_10->clicked(); in ../PIZZA/mainwindow.cpp:38 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_11->clicked(); in ../PIZZA/mainwindow.cpp:39 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_12->clicked(); in ../PIZZA/mainwindow.cpp:40 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_13->clicked(); in ../PIZZA/mainwindow.cpp:41 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_14->clicked(); in ../PIZZA/mainwindow.cpp:42 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_15->clicked(); in ../PIZZA/mainwindow.cpp:43 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_16->clicked(); in ../PIZZA/mainwindow.cpp:44 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_17->clicked(); in ../PIZZA/mainwindow.cpp:45 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_18->clicked(); in ../PIZZA/mainwindow.cpp:46 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_19->clicked(); in ../PIZZA/mainwindow.cpp:47 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_20->clicked(); in ../PIZZA/mainwindow.cpp:48 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_21->clicked(); in ../PIZZA/mainwindow.cpp:49 QObject::connect: (receiver name: 'pushButton') QObject::connect: No such slot QPushButton::ui->pushButton_22->clicked(); in ../PIZZA/mainwindow.cpp:50 QObject::connect: (receiver name: 'pushButton') libpng warning: iCCP: known incorrect sRGB profile
But it is strange actually works i can change the frequency of the tuner in the device. I was making debug run and the buttons was running in other thread (in thread_one)
-
@aurquiel said in Give me recomendations for use Qthread:
connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_21->clicked();));
I'm not sure exactly what you are trying to achieve but it looks like you want to invoke "start" on the USB thread whenever a button is pushed?
I think that you actually want to connect the buttons to slots on the USB thread, that would mean creating meaningful slots on the worker thread and connecting the button "clicked" signal to them.
Next up, the syntax for you connects are wrong.
connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton_10->clicked();));
You need to fully qualify the object then is sending the message not the slot name.
The slot name is "clicked()"
The object is ui->pushButton_10connect(thread_one,SIGNAL(started()),ui->pushButton_10,SLOT(clicked()));
However, that still won't work because "clicked()" is a signal not a slot.
What I would expect to see is something like thisconnect(ui->pushButtonChannel3, SIGNAL(clicked()), usbPullThread, SLOT(setChannel3()));
Lastly, and forgive me for being critical, PLEASE give you variables/members/functions meaningful names!
-
well, in that case : Praise the compiler for code optimization,:)
because this:
connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton->clicked();));
makes my heart hurt.
ui->pushButton->clicked(); is many things but above all its not a slot bit a Signal itself.
If it works, I guess this chains the started Signal to what ever pushButton is connected to.
but why dont you connect it this way than?
connect(ui->pushButton, SIGNAL(clicked()), MyObject, SLOT(mySlot())); // and the started Signal directly to the target slot connect(thread_one,SIGNAL(started()),MyObject,SLOT(mySlot()));
-
@aurquiel You should really read about Qt signals/slots, what you are doing is completely wrong:
connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(ui->pushButton->clicked();));
should be
connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(clicked()));
Why do you connect QThread::started signal to QPushButton::clicked signal? What do you want to achieve?
-
connect(thread_one,SIGNAL(started()),ui->pushButton,SLOT(clicked()));
this doesn't work
QObject::connect: No such slot QPushButton::clicked() in ../PIZZA/mainwindow.cpp:28 QObject::connect: (receiver name: 'pushButton')
I thing i must declare a new class only for threads with a public class to backend
and create the public slots in the thread class, the public slot of thread class will contain the backend functions.To get something like this
connect(ui->pushButtonChannel3, SIGNAL(clicked()), thread_one, SLOT(setChannel3()));
-
@aurquiel Yes, see my previous message "However, that still won't work because "clicked()" is a signal not a slot."
What you need to do is extend your "backend" class (Q_OBJECT) with slots for the functions you want to perform
public slots: rescan(); setChannel1(); setChannel2(); setChannel3();
Then connect you UI events to those slots.
//MainWindow.cpp connect(ui->pushButtonChannel1, SIGNAL(clicked()), backend, SLOT(setChannel1())); connect(ui->pushButtonChannel2, SIGNAL(clicked()), backend, SLOT(setChannel2())); connect(ui->pushButtonChannel3, SIGNAL(clicked()), backend, SLOT(setChannel3()));
You will probably want to reconsider the exact method for doing this eventually e.g. have a "setChannel(int channelId();" slot on backend instead and then place some logic in the UI to handle that. That is to say that the clicked handlers are within MainWindow and MainWindow emits a signal specify a numeric channel or SSID. However, that's the next step.
-
yes but backend is not a thread, i am very confuse at this point how to create a thread for the signals of the buttons could be handle with this thread.
because in the connect() must have the signal clicked and the slot of the tread also have the signal of thread started
-
@aurquiel Backend does not need to be thread. Instead it is owned by a thread (I think you create that thread in MainWindow).
That is, the QThread HASA MyQObject (not MyQObject ISA QThread)
Backend is still your implementation of the USB/TV Tuner control.
Now the backend will receive events and process them (slots) in the context of the thread that owns it, not in the context of the thread that emitted the signal.
To summarise:
- Your backend does all the actual interfacing with the USB device
- Create a thread and move the backend object to it
- Start that thread
- The UI emits signals (such as QPushButton::clicked) and there is a connection between that signal and the backend object slot
- Because the backend object is owned by a different thread (and therefore has an event loop) it's slot functions are executed in the context of the thread that owns it e.g. the moveToThread argument and not in the UI context. Events are free to travel in the other direction e.g. you can "emit" from your backend thread.
That is, it is your backend object that does the processing, it is that object that you implement your functionality on (as slots). The thread you created and moved the backend object to is the thread context used to execute the slots.
This is quite a decent way of implementing the threading model as your backend object doesn't need to worry about threading models. Just let Qt handle the cross thread deferred call via it's event model using sig/slots.
-
just realized, in your example function:
//Channel 123TV void MainWindow::on_pushButton_2_clicked() { //Initilize turnner and demulator usb_and_channels->initialize_tuner_demulator(); //Tune frequency usb_and_channels->tune_in(521000); }
you access usb_and_channels and manipulate it. But you moved it previously to a different Thread
//Moving channels object to thread_one usb_and_channels->moveToThread(thread_one);
Dont do that
Allways use Signal/Slots, or Mutex, for cross-thread access, or your programm will eventually crash. -
How to move the backend object to the thread for get the public slot function of backend
backend *usb_and_channels=new backend; QThread *thread_one = new QThread(); connect(ui->pushButton,SIGNAL(ui->pushButton->clicked()),thread_one,SLOT()); thread_one->start();
QThread *thread_one = new QThread(I MUST ADD IT HERE I THIS BUT HOW);
-
class backend : QObject { Q_OBJECT backend(QObject * parent = 0) : QObject(parent) { } public slots: void go(); private: // ..... }; //.... backend * usb_and_channels = new backend(); QThread * thread_one = new QThread(); usb_and_channels->moveToThread(thread_one); connect(ui->pushButton, SIGNAL(clicked()), usb_and_channels, SLOT(go())); thread_one->start();
"go" will be called in the context of "thread_one" not the context of the UI (main) thread.