GteThreadSafeQueue.h
Go to the documentation of this file.
1 // David Eberly, Geometric Tools, Redmond WA 98052
2 // Copyright (c) 1998-2017
3 // Distributed under the Boost Software License, Version 1.0.
4 // http://www.boost.org/LICENSE_1_0.txt
5 // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
6 // File Version: 3.0.0 (2016/06/19)
7 
8 #pragma once
9 
10 #include <GTEngineDEF.h>
11 #include <mutex>
12 #include <queue>
13 
14 namespace gte
15 {
16 
17 template <typename Element>
19 {
20 public:
21  // Construction and destruction.
22  virtual ~ThreadSafeQueue();
23  ThreadSafeQueue(size_t maxNumElements = 0);
24 
25  // All the operations are thread-safe.
26  size_t GetMaxNumElements() const;
27  size_t GetNumElements() const;
28  bool Push(Element const& element);
29  bool Pop(Element& element);
30 
31 protected:
33  std::queue<Element> mQueue;
34  mutable std::mutex mMutex;
35 };
36 
37 
38 template <typename Element>
40 {
41 }
42 
43 template <typename Element>
45  :
46  mMaxNumElements(maxNumElements)
47 {
48 }
49 
50 template <typename Element>
52 {
53  size_t maxNumElements;
54  mMutex.lock();
55  {
56  maxNumElements = mMaxNumElements;
57  }
58  mMutex.unlock();
59  return maxNumElements;
60 }
61 
62 template <typename Element>
64 {
65  size_t numElements;
66  mMutex.lock();
67  {
68  numElements = mQueue.size();
69  }
70  mMutex.unlock();
71  return numElements;
72 }
73 
74 template <typename Element>
75 bool ThreadSafeQueue<Element>::Push(Element const& element)
76 {
77  bool pushed;
78  mMutex.lock();
79  {
80  if (mQueue.size() < mMaxNumElements)
81  {
82  mQueue.push(element);
83  pushed = true;
84  }
85  else
86  {
87  pushed = false;
88  }
89  }
90  mMutex.unlock();
91  return pushed;
92 }
93 
94 template <typename Element>
95 bool ThreadSafeQueue<Element>::Pop(Element& element)
96 {
97  bool popped;
98  mMutex.lock();
99  {
100  if (mQueue.size() > 0)
101  {
102  element = mQueue.front();
103  mQueue.pop();
104  popped = true;
105  }
106  else
107  {
108  popped = false;
109  }
110  }
111  mMutex.unlock();
112  return popped;
113 }
114 
115 
116 }
size_t GetNumElements() const
size_t GetMaxNumElements() const
bool Push(Element const &element)
bool Pop(Element &element)
ThreadSafeQueue(size_t maxNumElements=0)
std::queue< Element > mQueue


geometric_tools_engine
Author(s): Yijiang Huang
autogenerated on Thu Jul 18 2019 04:00:01