I'm sorry to say that but your code doesn't make much sense... To handle a circular buffer, regardless of the number of consumers you only need one semaphore and optionally one mutex (but you can avoid having it for example by using QAtomicPointer).
Here is a rough implementation of a circular buffer (let's assume it holds integers, for simplicity):
class CircularBuffer {
public:
CircularBuffer(int size), m_sem(0) {
m_data = new int(size);
m_firstToRead = 0;
m_firstToWrite = 0;
m_size = size;
}
int read() {
m_sem.acquire(1);
m_mutex.lock(); // protect m_firstToRead
int val = m_data[m_firstToRead];
m_firstToRead = (m_firstToRead+1) % m_size;
m_mutex.unlock();
return val;
}
void write(int val) {
m_data[m_firstToWrite] = val;
m_firstToWrite = (m_firstToWrite+1) % m_size;
m_sem.release(1);
}
private:
int m_firstToRead;
int m_firstToWrite;
int m_size;
};
class CircularBuffer {
public:
CircularBuffer(int size), m_sem(0) {
m_data = new int(size);
m_firstToRead = 0;
m_firstToWrite = 0;
m_size = size;
}
int read() {
m_sem.acquire(1);
m_mutex.lock(); // protect m_firstToRead
int val = m_data[m_firstToRead];
m_firstToRead = (m_firstToRead+1) % m_size;
m_mutex.unlock();
return val;
}
void write(int val) {
m_data[m_firstToWrite] = val;
m_firstToWrite = (m_firstToWrite+1) % m_size;
m_sem.release(1);
}
private:
QSemaphore m_sem;
int m_firstToRead;
int m_firstToWrite;
int m_size;
QMutex m_mutex;
};
To copy to clipboard, switch view to plain text mode
If you want more than one producer, you need to protect m_firstToWrite as well.
If you need more buffers, or a buffer of buffers, just repeat the pattern. Allocating an array of arrays of semaphores is probably a very bad idea.
Bookmarks