Skip to content
This repository has been archived by the owner on Jan 6, 2020. It is now read-only.

Safe Queue

justinemclevy edited this page Jan 23, 2014 · 2 revisions

Back

Motivation

This is an extension to the std::queue, with internal mutex ensuring a safe operation under the multi-threading environment.

Examples

#include "maidsafe/common/safe_queue.h"
#include <iostream>
#include <thread>

void Push(maidsafe::SafeQueue<int>& safe_queue) {
  for(int i(1); i < 100; ++i)
    safe_queue.push(i);
}

void Pop(maidsafe::SafeQueue<int>& safe_queue) {
  while (safe_queue.size() > 0)
    safe_queue.WaitAndPop();
}

int main() {
  maidsafe::SafeQueue<int> safe_queue;
  std::thread t1(Push, safe_queue);
  std::thread t2(Pop, safe_queue);
  t1.join();
  t2.join();
  if (safe_queue.Empty())
    std::out << "Error" << std::endl;
  return 0;
}

Reference

template<typename T>
class SafeQueue {
 public:
  SafeQueue();
  bool Empty() const;
  size_t Size() const;
  void Push(T element);
  bool TryPop(T &element);
  void WaitAndPop(T &element);
 private:
 ....

Back