GNSS-SDR  0.0.13
An Open Source GNSS Software Defined Receiver
concurrent_queue.h
Go to the documentation of this file.
1 /*!
2  * \file concurrent_queue.h
3  * \brief Interface of a thread-safe std::queue
4  * \author Javier Arribas, 2011. jarribas(at)cttc.es
5  *
6  * -----------------------------------------------------------------------------
7  *
8  * Copyright (C) 2010-2020 (see AUTHORS file for a list of contributors)
9  *
10  * GNSS-SDR is a software defined Global Navigation
11  * Satellite Systems receiver
12  *
13  * This file is part of GNSS-SDR.
14  *
15  * SPDX-License-Identifier: GPL-3.0-or-later
16  *
17  * -----------------------------------------------------------------------------
18  */
19 
20 #ifndef GNSS_SDR_CONCURRENT_QUEUE_H
21 #define GNSS_SDR_CONCURRENT_QUEUE_H
22 
23 #include <chrono>
24 #include <condition_variable>
25 #include <mutex>
26 #include <queue>
27 #include <thread>
28 
29 template <typename Data>
30 
31 /*!
32  * \brief This class implements a thread-safe std::queue
33  *
34  * Thread-safe object queue which uses the library
35  * boost_thread to perform MUTEX based on the code available at
36  * https://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
37  */
38 class Concurrent_Queue
39 {
40 public:
41  void push(Data const& data)
42  {
43  std::unique_lock<std::mutex> lock(the_mutex);
44  the_queue.push(data);
45  lock.unlock();
46  the_condition_variable.notify_one();
47  }
48 
49  bool empty() const
50  {
51  std::unique_lock<std::mutex> lock(the_mutex);
52  return the_queue.empty();
53  }
54 
55  bool try_pop(Data& popped_value)
56  {
57  std::unique_lock<std::mutex> lock(the_mutex);
58  if (the_queue.empty())
59  {
60  return false;
61  }
62  popped_value = the_queue.front();
63  the_queue.pop();
64  return true;
65  }
66 
67  void wait_and_pop(Data& popped_value)
68  {
69  std::unique_lock<std::mutex> lock(the_mutex);
70  while (the_queue.empty())
71  {
72  the_condition_variable.wait(lock);
73  }
74  popped_value = the_queue.front();
75  the_queue.pop();
76  }
77 
78  bool timed_wait_and_pop(Data& popped_value, int wait_ms)
79  {
80  std::unique_lock<std::mutex> lock(the_mutex);
81  if (the_queue.empty())
82  {
83  the_condition_variable.wait_for(lock, std::chrono::milliseconds(wait_ms));
84  if (the_queue.empty())
85  {
86  return false;
87  }
88  }
89  popped_value = the_queue.front();
90  the_queue.pop();
91  return true;
92  }
93 
94 private:
95  std::queue<Data> the_queue;
96  mutable std::mutex the_mutex;
97  std::condition_variable the_condition_variable;
98 };
99 
100 #endif // GNSS_SDR_CONCURRENT_QUEUE_H
This class implements a thread-safe std::queue.