QThread
is not just a thread, it is also a thread manager. If you want your thread to play Qt, then QThread
is the way to go. Qt is event driven, as is most of modern programming. That's a little more complex and flexible than "make a thread run a function".
In Qt, you'd typically create a worker together with a QThread
, move the worker to that thread, then every function invoked by the event system for that worker object will be executed in the thread the worker object has affinity to.
So you can encapsulate your functionality in different worker object, say SafetyChecker
, Printer
, ServoDriver
, JetDriver
and so on, create an instance of each, move it to a dedicated thread and you are set. You still can invoke functions that would "block" instead of using fine grained events, and use atomics or mutexes to do inter-thread synchronization. There is nothing wrong with that, as long as you don't block the main/gui thread.
You would probably not want to do your printer code event driven, since in a multithreaded scenario that would involve queued connections, which are marginally slower than direct connections or even virtual dispatch. So much so that if you make your multithreading too fine grained, you are likely to actually experience a huge performance hit.
That being said, using Qt's non-gui stuff has its own merits, it will allow you to make a cleaner and more flexible design much easier, and you will still get the benefits of multithreading if you implement things properly. You can still use an event driven approach to manage the whole thing, it will be significantly easier than using only std::thread
, which is a much lower level construct. You can use event driven approach to setting up, configuring, monitoring and managing the design, while the critical parts can be executed in blocking functions in auxiliary threads to achieve fine grained control at the lowest possible synchronization overhead.
To clarify - the answer does not focus on async task execution, because the other two answers already do, and because as I mentioned in the comments, async tasks are not really intended for control applications. They are suited to the execution of small tasks, which still take more time than you'd want to block the main thread for. As a recommended guideline, everything that takes more than 25 msec is preferable to be executed async. Whereas printing is something that may take minutes or even hours, and imply continuously running control functions, in parallel and using synchronization. Async tasks won't give you the performance, latency and order guarantees for control applications.