Data Sharing in Qt Streams

I'm new to Qt, so please excuse the simplicity of the question, but I'm a little confused about the Qt thread. Let's say I have 3 threads: the default GUI main thread and 2 threads of my own creation (called WorkerThread). Each of my WorkerThreads inherits from QThread and is a constant thread that so often wakes up and sends data from the socket and publication status in the GUI element. What is the best way: 1) to allow the GUI thread to set data in the WorkerThread object that the WorkerThread thread can use? 2) allow WorkerThread to send status to the GUI thread that will be displayed to the user? 3) Allow both WorkerThreads to use the same socket?

As you can see from the documentation, when I create a WorkerThread object, it belongs to the creating thread (with the exception of the run method, which is the new thread). So how to set data for a new thread to execute? Should all the data that the new stream uses are global? For example, I would like the GUI to allow the user to select the type of package for each of WorkerThreads to send when they wake up. I assumed that I would put some slots in WorkerThread that the GUI thread would signal. When the WorkerThread object received a SetPacketType signal, it would set a member variable, which the run method refers to each iteration. But after reading the documentation, I'm not sure if this is the way to do it. If the WorkerThread object belongs to the creating thread (the thread in the GUI in this case), then sending signals to it does not cross the boundaries of the threads?

Also, what is the proper technique for sharing sockets over threads?

Thanks in advance.

+4
source share
1 answer

With Qt, the easiest way to transfer information between streams is to use signals and slots. Qt automatically uses queue signals for connections between streams (see Qt :: ConnectionType ), which ensures that the signal can be output from one stream, but the slot will be executed in the stream of the receiver object.

If the data is sent between threads (the work to be done or the status information), this is what Qt can automatically queue for (e.g. QStrings, built-in types such as int and double, and others) and then pass information as arguments to a signal / slot is the best way to send information. If large or complex data is shared, you need to either use qRegisterMetaType to allow Qt to copy the data, or pass a pointer to a thread-safe object. Unlike what Pie_Jesu said, streams share the address space, so you can share pointers; just make sure that one thread interaction with a shared object will not interfere with other thread interactions.

QTcpSocket is not thread safe (it is only reentrant according to the Qt documentation), so if you are sharing a socket, you will have to be responsible for ensuring that the threads do not use the socket in conflicting ways.

+4
source

Source: https://habr.com/ru/post/1433600/


All Articles