Hi,
I don't understand some details about the Semaphores Example QSemaphore.

For simplicity I'll paste the example code:

Global Variables
Qt Code:
  1. const int DataSize = 100000;
  2.  
  3. const int BufferSize = 8192;
  4. char buffer[BufferSize];
  5.  
  6. QSemaphore freeBytes(BufferSize);
  7. QSemaphore usedBytes;
To copy to clipboard, switch view to plain text mode 

Producer Class
Qt Code:
  1. class Producer : public QThread
  2. {
  3. public:
  4. void run() Q_DECL_OVERRIDE
  5. {
  6. qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
  7. for (int i = 0; i < DataSize; ++i) {
  8. freeBytes.acquire();
  9. buffer[i % BufferSize] = "ACGT"[(int)qrand() % 4];
  10. usedBytes.release();
  11. }
  12. }
  13. };
To copy to clipboard, switch view to plain text mode 

Consumer Class

Qt Code:
  1. class Consumer : public QThread
  2. {
  3. Q_OBJECT
  4. public:
  5. void run() Q_DECL_OVERRIDE
  6. {
  7. for (int i = 0; i < DataSize; ++i) {
  8. usedBytes.acquire();
  9. fprintf(stderr, "%c", buffer[i % BufferSize]);
  10. freeBytes.release();
  11. }
  12. fprintf(stderr, "\n");
  13. }
  14.  
  15. signals:
  16. void stringConsumed(const QString &text);
  17.  
  18. protected:
  19. bool finish;
  20. };
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?