Generally, you must decide who will be responsible for managing the flow. Is this device or main window? Or maybe some kind of device manager. In your case, the device should probably control its own stream, so if you don't want to subclass it, use the composition:
class Device : QObject { Q_OBJECT public: Device(QObject * parent = NULL); void Start(); void Stop(); private slots: void MsgLoop(); signals: void sMsgArrived(); private: QThread thread; bool stopThread; }; Device::Device(QObject * parent) : QObject(parent) { moveToThread(&thread); connect(&thread, SIGNAL(started()), this, SLOT(MsgLoop())); } void Device::Start() { stopThread = false; thread.start(); } void Device::Stop() { stopThread = true; thread.wait();
NOTE: stopping the thread will only work if ReadMsg is not really blocking. If you later decide to switch to read lock (and this will probably be appropriate for most cases), you will have to figure out how to stop the stream.
Fiktik
source share