[SOLVED]How to share data between threads
-
wrote on 10 Aug 2013, 16:37 last edited by
Hi!
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!
Regards,
Jake -
wrote on 10 Aug 2013, 17:02 last edited by
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.
See:
"Producer-Consumer Problem":http://tinyurl.com/kls77un -
wrote on 10 Aug 2013, 17:13 last edited by
Qt Example:
@QMutex mutex;
QSemaphore semFree(8);
QSemaphore semAvail(0);QList<MyData> buffer;
QProducerThread::run()
{
while(true)
{
MyData data = produceItem();
semFree.acquire();
mutex.lock();
buffer.append(data);
mutex.unlock();
semAvail.release();
}
}QConsumerThread::run()
{
while(true)
{
MyData data;
semAvail.acquire();
mutex.lock();
data = buffer.takeFirst();
mutex.unlock();
semFree.release();
doSomethingWith(data);
}
}@--
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...
-
wrote on 11 Aug 2013, 12:27 last edited by
Thanks! It works.
Seconds thread is using queued connection with additional delay (10 milliseconds I think) just to keep GUI responsive.
1/4