Hi,
I don't understand some details about the Semaphores Example QSemaphore.
For simplicity I'll paste the example code:
Global Variables
const int DataSize = 100000;
const int BufferSize = 8192;
char buffer[BufferSize];
const int DataSize = 100000;
const int BufferSize = 8192;
char buffer[BufferSize];
QSemaphore freeBytes(BufferSize);
QSemaphore usedBytes;
To copy to clipboard, switch view to plain text mode
Producer Class
{
public:
void run() Q_DECL_OVERRIDE
{
qsrand
(QTime(0,
0,
0).
secsTo(QTime::currentTime()));
for (int i = 0; i < DataSize; ++i) {
freeBytes.acquire();
buffer[i % BufferSize] = "ACGT"[(int)qrand() % 4];
usedBytes.release();
}
}
};
class Producer : public QThread
{
public:
void run() Q_DECL_OVERRIDE
{
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
for (int i = 0; i < DataSize; ++i) {
freeBytes.acquire();
buffer[i % BufferSize] = "ACGT"[(int)qrand() % 4];
usedBytes.release();
}
}
};
To copy to clipboard, switch view to plain text mode
Consumer Class
{
Q_OBJECT
public:
void run() Q_DECL_OVERRIDE
{
for (int i = 0; i < DataSize; ++i) {
usedBytes.acquire();
fprintf(stderr, "%c", buffer[i % BufferSize]);
freeBytes.release();
}
fprintf(stderr, "\n");
}
signals:
void stringConsumed
(const QString &text
);
protected:
bool finish;
};
class Consumer : public QThread
{
Q_OBJECT
public:
void run() Q_DECL_OVERRIDE
{
for (int i = 0; i < DataSize; ++i) {
usedBytes.acquire();
fprintf(stderr, "%c", buffer[i % BufferSize]);
freeBytes.release();
}
fprintf(stderr, "\n");
}
signals:
void stringConsumed(const QString &text);
protected:
bool finish;
};
To copy to clipboard, switch view to plain text mode
The questions are:
- does freeBytes(BufferSize) reserves BufferSize resources or not?
- how the consumer is blocked waiting for the usedBytes semaphore to be released?
- The example say "Once the producer has put one byte in the buffer, freeBytes.available() is BufferSize - 1 and usedBytes.available() is 1" why the freeBytes is decremented and the usedBytes semaphore is incremented?
Bookmarks