
Originally Posted by
wysota
Producer/consumer problem is usually solved using semaphores or wait conditions, depending on the type of pattern you are dealing with (mainly if the number of producer "slots" is limited - i.e. when you produce data into a buffer of limited size).
In this particular case, the container cannot be limited in size...even though it will likely have little "pressure" (1:1 - 3:1 consumers : producers, with each pop/push separated by seconds)... it is critical that the information produced by the producer is not lost....
I ended up with:
#ifndef ASYNC_queueH
#define ASYNC_queueH
#include <QThread>
#include <QQueue>
template<class T> class QAsyncQueue
{
public:
QAsyncQueue(uint _max = -1)
: _max(max)
{
}
~QAsyncQueue()
{
clean();
}
uint count()
{
_mutex.lock();
int count = _queue.count();
_mutex.unlock();
return count;
}
bool isFull()
{
if (-1 == _max)
return false;
_mutex.lock();
int count = _queue.count();
_mutex.unlock();
return count >= max_;
}
bool isEmpty()
{
_mutex.lock();
bool empty = _queue.isEmpty();
_mutex.unlock();
return empty;
}
void clean()
{
_mutex.lock();
_queue.clear();
_mutex.unlock();
}
void push(const T& t)
{
_mutex.lock();
_queue.enqueue(t);
_mutex.unlock();
}
T pull()
{
_mutex.lock();
T i = _queue.dequeue();
_mutex.unlock();
return i;
}
private:
QQueue<T> _queue;
int _max;
};
#endif
#ifndef ASYNC_queueH
#define ASYNC_queueH
#include <QThread>
#include <QQueue>
template<class T> class QAsyncQueue
{
public:
QAsyncQueue(uint _max = -1)
: _max(max)
{
}
~QAsyncQueue()
{
clean();
}
uint count()
{
_mutex.lock();
int count = _queue.count();
_mutex.unlock();
return count;
}
bool isFull()
{
if (-1 == _max)
return false;
_mutex.lock();
int count = _queue.count();
_mutex.unlock();
return count >= max_;
}
bool isEmpty()
{
_mutex.lock();
bool empty = _queue.isEmpty();
_mutex.unlock();
return empty;
}
void clean()
{
_mutex.lock();
_queue.clear();
_mutex.unlock();
}
void push(const T& t)
{
_mutex.lock();
_queue.enqueue(t);
_mutex.unlock();
}
T pull()
{
_mutex.lock();
T i = _queue.dequeue();
_mutex.unlock();
return i;
}
private:
QQueue<T> _queue;
QMutex _mutex;
int _max;
};
#endif
To copy to clipboard, switch view to plain text mode
probably not state-of-the-art C++ code, but it seems to work... I declare one of these queue as a global or static and threads are sharing it....
so from your answers so far, Qt is providing classic tools for threading...locking and such must be done by hand... there is no high level class hiding all this...
thanks for the answers so far!
Bookmarks