GNSS-SDR  0.0.19
An Open Source GNSS Software Defined Receiver
concurrent_map.h
Go to the documentation of this file.
1 /*!
2  * \file concurrent_map.h
3  * \brief Interface of a thread-safe std::map
4  * \author Javier Arribas, 2011. jarribas(at)cttc.es
5  *
6  * -----------------------------------------------------------------------------
7  *
8  * GNSS-SDR is a Global Navigation Satellite System software-defined receiver.
9  * This file is part of GNSS-SDR.
10  *
11  * Copyright (C) 2010-2020 (see AUTHORS file for a list of contributors)
12  * SPDX-License-Identifier: GPL-3.0-or-later
13  *
14  * -----------------------------------------------------------------------------
15  */
16 
17 #ifndef GNSS_SDR_CONCURRENT_MAP_H
18 #define GNSS_SDR_CONCURRENT_MAP_H
19 
20 #include <map>
21 #include <mutex>
22 #include <utility>
23 
24 /** \addtogroup Core
25  * \{ */
26 /** \addtogroup Core_Receiver core_receiver
27  * \{ */
28 
29 
30 template <typename Data>
31 
32 
33 /*!
34  * \brief This class implements a thread-safe std::map
35  *
36  */
38 {
39  typedef typename std::map<int, Data>::iterator Data_iterator; // iterator is scope dependent
40 public:
41  void write(int key, Data const& data)
42  {
43  std::unique_lock<std::mutex> lock(the_mutex);
44  Data_iterator data_iter;
45  data_iter = the_map.find(key);
46  if (data_iter != the_map.end())
47  {
48  data_iter->second = data; // update
49  }
50  else
51  {
52  the_map.insert(std::pair<int, Data>(key, data)); // insert SILENTLY fails if the item already exists in the map!
53  }
54  lock.unlock();
55  }
56 
57  std::map<int, Data> get_map_copy()
58  {
59  std::unique_lock<std::mutex> lock(the_mutex);
60  std::map<int, Data> map_aux = the_map;
61  lock.unlock();
62  return map_aux;
63  }
64 
65  size_t size()
66  {
67  std::unique_lock<std::mutex> lock(the_mutex);
68  size_t size_ = the_map.size();
69  lock.unlock();
70  return size_;
71  }
72 
73  bool read(int key, Data& p_data)
74  {
75  std::unique_lock<std::mutex> lock(the_mutex);
76  Data_iterator data_iter;
77  data_iter = the_map.find(key);
78  if (data_iter != the_map.end())
79  {
80  p_data = data_iter->second;
81  lock.unlock();
82  return true;
83  }
84  lock.unlock();
85  return false;
86  }
87 
88 private:
89  std::map<int, Data> the_map;
90  mutable std::mutex the_mutex;
91 };
92 
93 
94 /** \} */
95 /** \} */
96 #endif // GNSS_SDR_CONCURRENT_MAP_H
This class implements a thread-safe std::map.