Take the example from the Qt docs: one creates a controller and a worker, moves the worker to the specific thread and starts the thread. Start/stop triggering are done via signal/slot.
Now assume that the doWork
method depends on some parameter (for example an output rate of intermediate results (in form of some visualization)) and one would like to tweak that parameter via a user interface while the function is running.
If one uses the signal/slot mechanism (between interface and worker) this won't work, as the receiving slot of the worker will be queued after the running event loop and thus will be executed after doWork
finished.
I came up with the following solutions:
Method 1:
Make the parameter public
in Worker
and change it directly via the interface.
class Worker : public QObject
{
Q_Object
public:
int parameter;
...
}
Interface::updateParameter(int p) { worker_instance.parameter = p; }
Method 2:
Move the parameter to either the interface itself or some extra class (living in another thread than the worker) and make the worker load it each time it's required.
class Interface : public QWidget
{
Q_Object
private:
int parameter;
public:
int getParameter() { return parameter; }
...
}
Worker::doWork() {
...
interface_instance.getParameter(); // load parameter;
...
}
Instead of placing the parameter within the interface one could place it in another class and interact with this class via signal/slot mechanism.
Regarding ease of use I'd definitely prefer Method 1. It also makes things stay where they actually belong to. Method 2 doesn't really seem to offer an advantage over Method 1. Any opinions on that?
Also are there any different approaches to handle things like that? For example viewing an animation, I guess one wants to enable adjustemt of the animation speed which somehow requires a hook into the animation process.
Do you have any ideas or knowledge on this topic?