GNSS-SDR  0.0.21
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 public:
40  void write(int key, Data const& data)
41  {
42  std::lock_guard<std::mutex> lock(the_mutex);
43  auto data_iter = the_map.find(key);
44  if (data_iter != the_map.end())
45  {
46  data_iter->second = data; // update
47  }
48  else
49  {
50  the_map.insert(std::pair<int, Data>(key, data)); // insert does not overwrite if the item already exists in the map!
51  }
52  }
53 
54  std::map<int, Data> get_map_copy() const&
55  {
56  std::lock_guard<std::mutex> lock(the_mutex);
57  return the_map; // This implicitly creates a copy
58  }
59 
60  std::map<int, Data> get_map_copy() &&
61  {
62  std::lock_guard<std::mutex> lock(the_mutex);
63  return std::move(the_map);
64  }
65 
66  size_t size() const
67  {
68  std::lock_guard<std::mutex> lock(the_mutex);
69  return the_map.size();
70  }
71 
72  bool read(int key, Data& p_data) const
73  {
74  std::lock_guard<std::mutex> lock(the_mutex);
75  auto data_iter = the_map.find(key);
76  if (data_iter != the_map.end())
77  {
78  p_data = data_iter->second;
79  return true;
80  }
81  return false;
82  }
83 
84 private:
85  std::map<int, Data> the_map;
86  mutable std::mutex the_mutex;
87 };
88 
89 
90 /** \} */
91 /** \} */
92 #endif // GNSS_SDR_CONCURRENT_MAP_H
This class implements a thread-safe std::map.