Kata Step Nine

Our queue isn’t really “bounded” yet. We need to tell the Producer to stop shoving items at us when our queue becomes full. So we have to define a size, or bound, for our queue.

We'll update our fixture to give our queue an easily testable bound:

BoundedQueueTest.cpp

class BoundedQueueTest : public ::testing::Test {
public:
        ...
        BoundedQueueTest() : q(producer, consumer, BOUND) { }
        static const size_t BOUND = 3;
        ...
};

TEST_F(BoundedQueueTest, EnqueuePausesProducerWhenQueueIsFull) {
        EXPECT_CALL(producer, Pause());
        q.enqueue(4);
        q.enqueue(4);
        q.enqueue(4);
}

Oh, bother. This doesn't compile.

See if you can make this compile, or read on:











Right, we just have to change our BoundedQueue constructor to accept the size parameter. If we supply a default value, we don't have to change existing calls to the constructor (like the ones in our first two tests).

BoundedQueue.h

        BoundedQueue(QueueControl& producer, QueueControl& consumer, size_t size = 100) ... 

Red bar!

See if you can make the test pass, or read on:











The queue needs to remember its bound, and notify its producer when it's full. Oh, guess that means it has to remember its producer, too.

BoundedQueue.h

template <typename T>
class BoundedQueue {
public:
        BoundedQueue(QueueControl& producer, QueueControl& consumer, size_t size = 100) 
                : producer(producer), consumer(consumer), max_size(size) {
                ...
        }
        ...
private:
        ...
        QueueControl& producer;
        size_t max_size;
};

And the queue needs to notify its producer when it's full.

BoundedQueue.h

        void enqueue(const T& item) {
                q.push(item);
                if (q.size() == 1) {
                        consumer.Resume();
                }
                if (q.size() == max_size) {
                        producer.Pause();
                }
        }

Green bar, 7 passing tests!

Go to BoundedQueueKataSummary.... or go back

BoundedQueueKataStepNine (last edited 2010-01-17 00:51:21 by KayJohansen)