Reputation: 567
I have a worker thread object living in a different thread from my main GUI thread created as in the code at the bottom. I need to pass data between the threads without copying the data since the data is quite large (in this case a tree for use in a QAbstractItemModel so don't know how I'd copy it anyways...) and thus will pass a pointer to the data. This will be done using signals and slots. If the main GUI thread and the worker thread only ever process the data during their turn, do I need synchronization primitives/mutexes?
So the logic flow is like this. The worker threads constructs the data, then passes control to the GUI thread with a signal/slot connection. After this signal/slot connection the worker thread no longer does anything with the data. Control lies exclusively in the main GUI thread. Once the program has to process the data it again passes a pointer to the data to worker thread via signal/slot to be processed. After this signal/slot connection the GUI thread no longer does anything with the data. Considering the threads take their turns and signal/slot connections are thread-safe do I need synchronization primitives/mutexes at all?
workerThread = new QThread(this);
workerThread->start();
worker = new Worker;
worker->moveToThread(workerThread);
Upvotes: 0
Views: 119
Reputation: 41
The GUI thread is called the master thread in general in the context of QT. This master thread has a living event queue. This queue is thread-safe as a result you do not need any synchronization here. However, you are sharing a common memory field among the threads, including your master and worker threads. Here you need to be careful about the shared data in some cases. Let me clarify it by giving some examples. First of all, if you are sure that there is only one thread working on the data shared at the same time then you do not need any synchronization at all. In some cases, you may want to handle error cases in both threads. In these cases, you may want to access the shared data directly in either thread. As a result, you will need some locking mechanisms but I do not suggest you this approach.
I think the safest way to deal with this is by using event-driven architecture and I reckon that you are already doing this in your design. Just signal your master thread from one worker thread and do nothing in your worker thread until you get an event from the master thread and vice verse. I assume you have only one worker thread in your system.
Please note that your worker thread has also a living event queue already.
As a conclusion, if you have a clear patter and flow in your design with respect to the shared data process then you will not need any locking mechanism.
Upvotes: 1