PDA

View Full Version : communicating between threads



freekill
26th November 2009, 05:12
I'm trying to acquire data which is stored in a buffer. The instance of the buffer is private to my producer thread. How will I be able to access this data in my consumer thread?

This is the producer thread header.



#ifndef COMPUTINGTHREAD_H
#define COMPUTINGTHREAD_H

#include <QThread>

class ImageBuffer;

class ComputingThread : public QThread
{
public:
ComputingThread();
~ComputingThread();

void haltComputing();
void startTransmitting();
void stopTransmitting();

protected:
void run();

private:
volatile bool halt;
volatile bool transmit;
ImageBuffer* imageBuffer;
};

#endif

Lykurg
26th November 2009, 08:36
You can use signal/slots. Even with threads. Or you use a normal pointer and access the data via a getter function.

Gnurou
27th November 2009, 08:13
As said previously, you can emit a signal from your producer thread. If the receiving object has been created in your consumer thread, its slot will execute in the consumer thread's event loop. A pointer to your buffer can then be passed as argument, or just anything that would be relevant.

Be careful that such inter-threads signals are by default asynchronous - that is, you have to make sure by yourself that the producer's buffer will remain valid until the consumer has finished with it. You can achieve synchronous behavior by playing with the type argument of QObject::connect() (http://qt.nokia.com/doc/4.5/qobject.html#connect).