[SOLVED]How to share data between threads
I'm trying to setup a communication between 2 threads.
First thread is generating data and sending it to a second one. Second thread then merges as much data as possible in the given time and sends it to a GUI to be displayed. Given time is a few milliseconds so that GUI doesn't crashes. Both threads have while (true) condition. I cannot use Qt::QuedConnection because of that
and Qt::DirectConnection causes SIGSEGV when data is accessed from both threads at the same time.
Data = QList<QString>
First threads appends. Seconds thread reads and removes.
How can I achieve stable communication? I tried with QMutex, but with no effect.
Thanks in advance!
Sounds like you have a classical producer/consumer problem here, which can be solved using a shared (ring) Buffer plus two Semaphores and a Mutex.
MyData data = produceItem();
data = buffer.takeFirst();
BTW: The second thread (consumer thread) should definitely use a queued connection to send the data to the GUI thread (event loop). The corresponding slot can then update the GUI (from the context of the "main" thread). Trying to access any GUI controls from a "background" thread will almost certainly lead to undefined behavior including crash...
Thanks! It works.
Seconds thread is using queued connection with additional delay (10 milliseconds I think) just to keep GUI responsive.