WPILibC++ 2023.4.3-108-ge5452e3
ConcurrentQueue.h
Go to the documentation of this file.
1//
2// Copyright (c) 2013 Juan Palacios juan.palacios.puyana@gmail.com
3// Subject to the BSD 2-Clause License
4// - see < http://opensource.org/licenses/BSD-2-Clause>
5//
6
7#ifndef WPIUTIL_WPI_CONCURRENTQUEUE_H_
8#define WPIUTIL_WPI_CONCURRENTQUEUE_H_
9
10#include <queue>
11#include <thread>
12#include <utility>
13
15#include "wpi/mutex.h"
16
17namespace wpi {
18
19template <typename T>
21 public:
22 bool empty() const {
23 std::unique_lock<wpi::mutex> mlock(mutex_);
24 return queue_.empty();
25 }
26
27 typename std::queue<T>::size_type size() const {
28 std::unique_lock<wpi::mutex> mlock(mutex_);
29 return queue_.size();
30 }
31
32 T pop() {
33 std::unique_lock<wpi::mutex> mlock(mutex_);
34 while (queue_.empty()) {
35 cond_.wait(mlock);
36 }
37 auto item = std::move(queue_.front());
38 queue_.pop();
39 return item;
40 }
41
42 void pop(T& item) {
43 std::unique_lock<wpi::mutex> mlock(mutex_);
44 while (queue_.empty()) {
45 cond_.wait(mlock);
46 }
47 item = queue_.front();
48 queue_.pop();
49 }
50
51 void push(const T& item) {
52 std::unique_lock<wpi::mutex> mlock(mutex_);
53 queue_.push(item);
54 mlock.unlock();
55 cond_.notify_one();
56 }
57
58 void push(T&& item) {
59 std::unique_lock<wpi::mutex> mlock(mutex_);
60 queue_.push(std::forward<T>(item));
61 mlock.unlock();
62 cond_.notify_one();
63 }
64
65 template <typename... Args>
66 void emplace(Args&&... args) {
67 std::unique_lock<wpi::mutex> mlock(mutex_);
68 queue_.emplace(std::forward<Args>(args)...);
69 mlock.unlock();
70 cond_.notify_one();
71 }
72
73 ConcurrentQueue() = default;
76
77 private:
78 std::queue<T> queue_;
79 mutable wpi::mutex mutex_;
81};
82
83} // namespace wpi
84
85#endif // WPIUTIL_WPI_CONCURRENTQUEUE_H_
Definition: ConcurrentQueue.h:20
void push(const T &item)
Definition: ConcurrentQueue.h:51
ConcurrentQueue(const ConcurrentQueue &)=delete
void pop(T &item)
Definition: ConcurrentQueue.h:42
std::queue< T >::size_type size() const
Definition: ConcurrentQueue.h:27
ConcurrentQueue & operator=(const ConcurrentQueue &)=delete
void push(T &&item)
Definition: ConcurrentQueue.h:58
void emplace(Args &&... args)
Definition: ConcurrentQueue.h:66
T pop()
Definition: ConcurrentQueue.h:32
ConcurrentQueue()=default
bool empty() const
Definition: ConcurrentQueue.h:22
Definition: AprilTagFieldLayout.h:18
::std::mutex mutex
Definition: mutex.h:17
::std::condition_variable condition_variable
Definition: condition_variable.h:16