[SOLVED]How to share data between threads
-
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 -
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 -
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...