Woman, Life, Freedom


Adaptive AUTOSAR
ARA public interface header documentation
concurrent_queue.h
1#ifndef CONCURRENT_QUEUE_H
2#define CONCURRENT_QUEUE_H
3
4#include <mutex>
5#include <queue>
6#include <atomic>
7
8namespace ara
9{
10 namespace com
11 {
12 namespace helper
13 {
16 template <typename T>
18 {
19 private:
20 std::mutex mMutex;
21 std::queue<T> mQueue;
22 std::atomic_size_t mSize;
23
24 public:
25 ConcurrentQueue() : mSize{0}
26 {
27 }
28
29 ~ConcurrentQueue() = default;
30
33 bool Empty() const noexcept
34 {
35 return mSize == 0;
36 }
37
42 bool TryEnqueue(T &&element)
43 {
44 std::unique_lock<std::mutex> _lock(mMutex, std::defer_lock);
45 if (_lock.try_lock())
46 {
47 mQueue.emplace(std::move(element));
48 ++mSize;
49 _lock.unlock();
50 return true;
51 }
52 else
53 {
54 return false;
55 }
56 }
57
62 bool TryEnqueue(const T &element)
63 {
64 std::unique_lock<std::mutex> _lock(mMutex, std::defer_lock);
65 if (_lock.try_lock())
66 {
67 mQueue.emplace(element);
68 ++mSize;
69 _lock.unlock();
70 return true;
71 }
72 else
73 {
74 return false;
75 }
76 }
77
81 bool TryDequeue(T &element)
82 {
83 std::unique_lock<std::mutex> _lock(mMutex, std::defer_lock);
84 if (_lock.try_lock())
85 {
86 element = std::move(mQueue.front());
87 mQueue.pop();
88 --mSize;
89 _lock.unlock();
90 return true;
91 }
92 else
93 {
94 return false;
95 }
96 }
97 };
98 }
99 }
100}
101
102#endif
Thread-safe wrapper around STL queue using locking mechanism.
Definition: concurrent_queue.h:18
bool TryEnqueue(const T &element)
Try to insert an element to the queue via copying.
Definition: concurrent_queue.h:62
bool TryDequeue(T &element)
Try to peek an element from the queue by removing it.
Definition: concurrent_queue.h:81
bool TryEnqueue(T &&element)
Try to insert an element to the queue via moving.
Definition: concurrent_queue.h:42
bool Empty() const noexcept
Indicate whether the queue is empty or not.
Definition: concurrent_queue.h:33