Queue

class Queue

template <class T>
class paddle::Queue

A thread-safe queue that automatically grows but never shrinks. Dequeue a empty queue will block current thread. Enqueue an element will wake up another thread that blocked by dequeue method.

For example.

paddle::Queue<int> q;
END_OF_JOB=-1
void thread1() {
  while (true) {
    auto job = q.dequeue();
    if (job == END_OF_JOB) {
      break;
    }
    processJob(job);
  }
}

void thread2() {
  while (true) {
     auto job = getJob();
     q.enqueue(job);
     if (job == END_OF_JOB) {
       break;
     }
  }
}

Public Functions

Queue()

Construct Function. Default capacity of Queue is zero.

~Queue()
void enqueue(const T &el)

enqueue an element into Queue.

Note
This method is thread-safe, and will wake up another blocked thread.
Parameters
  • el -

    The enqueue element.

void enqueue(T &&el)

enqueue an element into Queue.

Note
This method is thread-safe, and will wake up another blocked thread.
Parameters
  • el -

    The enqueue element. rvalue reference .

T dequeue()

Dequeue from a queue and return a element.

Note
this method will be blocked until not empty.

int size() const

Return size of queue.

Note
This method is not thread safe. Obviously this number can change by the time you actually look at it.

bool empty() const

is empty or not.

Return
true if empty.
Note
This method is not thread safe.

void waitEmpty()

wait util queue is empty

bool waitNotEmptyFor(int seconds)

wait queue is not empty at most for some seconds.

Return
true if queue is not empty. false if timeout.
Parameters
  • seconds -

    wait time limit.

class BlockingQueue

template <typename T>
class paddle::BlockingQueue

Public Functions

BlockingQueue(size_t capacity)

Construct Function.

Parameters
  • capacity -

    the max numer of elements the queue can have.

void enqueue(const T &x)

enqueue an element into Queue.

Note

This method is thread-safe, and will wake up another thread who was blocked because of the queue is empty.

If it’s size() >= capacity before enqueue, this method will block and wait until size() < capacity.

Parameters
  • x -

    The enqueue element, pass by reference .

T dequeue()

Dequeue from a queue and return a element.

Note

this method will be blocked until not empty.

this method will wake up another thread who was blocked because of the queue is full.

size_t size()

Return size of queue.

Note
This method is thread safe. The size of the queue won’t change until the method return.

size_t empty()

is empty or not.

Return
true if empty.
Note
This method is thread safe.