What's the difference between connecting the signal QTimer::timeout to my working
function and creating a worker thread with QThread?
When you connect some signal/slot pair from the objects which has the same thread affinity, then the connection is direct. What it means is in your case, the main thread creates the timer
, and also contains the slot
, so the signal
will be emitted in the main
thread and also will be processed in the main
thread (as the slot is also in the main thread).
When you connect some signal/slot pair from the objects which has the different thread affinity, then the connection is queued. That means signal emission and slot execution will run in different threads.
You are not really achieving concurrency, the timer signal and processing slot are executing in main thread sequentially.
So here are your options:
- If you want to process data in main thread, current code is ok.
- If you want to emit
timeout
in main thread and process data in different thread then create new class with the processing method and usemoveToThread
with object of that class.
The link you provided really has a different situation. In your case (correct me if I am wrong), you process data only when data is available, not just after a specified time. Your situation is much like traditional producer/consumer problem. My proposal is to not use QTimer
at all. Instead create a new class
with a slot
which will process data. Then emit
a signal from main thread when data is available, and connect if to the processing slot
. You will achieve real concurrency. In this case you will need to implement locking for shared data access, it is easy in Qt
, you can just use QMutexLocker