GNSS-SDR  0.0.13
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  * 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_MAP_H
21 #define GNSS_SDR_CONCURRENT_MAP_H
22 
23 #include <map>
24 #include <mutex>
25 #include <utility>
26 
27 
28 template <typename Data>
29 
30 
31 /*!
32  * \brief This class implements a thread-safe std::map
33  *
34  */
36 {
37  typedef typename std::map<int, Data>::iterator Data_iterator; // iterator is scope dependent
38 public:
39  void write(int key, Data const& data)
40  {
41  std::unique_lock<std::mutex> lock(the_mutex);
42  Data_iterator data_iter;
43  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 SILENTLY fails if the item already exists in the map!
51  }
52  lock.unlock();
53  }
54 
55  std::map<int, Data> get_map_copy()
56  {
57  std::unique_lock<std::mutex> lock(the_mutex);
58  std::map<int, Data> map_aux = the_map;
59  lock.unlock();
60  return map_aux;
61  }
62 
63  size_t size()
64  {
65  std::unique_lock<std::mutex> lock(the_mutex);
66  size_t size_ = the_map.size();
67  lock.unlock();
68  return size_;
69  }
70 
71  bool read(int key, Data& p_data)
72  {
73  std::unique_lock<std::mutex> lock(the_mutex);
74  Data_iterator data_iter;
75  data_iter = the_map.find(key);
76  if (data_iter != the_map.end())
77  {
78  p_data = data_iter->second;
79  lock.unlock();
80  return true;
81  }
82  lock.unlock();
83  return false;
84  }
85 
86 private:
87  std::map<int, Data> the_map;
88  mutable std::mutex the_mutex;
89 };
90 
91 #endif // GNSS_SDR_CONCURRENT_MAP_H
This class implements a thread-safe std::map.