thread_safe_map.hpp
Go to the documentation of this file.
1 /*
2 * Copyright 2011 Shadow Robot Company Ltd.
3 *
4 * This program is free software: you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the Free
6 * Software Foundation version 2 of the License.
7 *
8 * This program is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
11 * more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16 
29 #ifndef _THREAD_SAFE_MAP_HPP_
30 #define _THREAD_SAFE_MAP_HPP_
31 
32 #include <boost/smart_ptr.hpp>
33 #include <boost/thread/shared_mutex.hpp>
34 #include <boost/thread/mutex.hpp>
35 
36 #include <map>
37 #include <vector>
38 #include <iostream>
39 #include <utility>
40 #include <string>
41 
42 namespace threadsafe
43 {
44 template<class T>
45 class Map
46 {
47 public:
48  Map()
49  {
50  mutex_ = boost::shared_ptr<boost::shared_mutex>(new boost::shared_mutex());
52  };
53 
54  ~Map()
55  {
56  };
57 
58  T find(std::string first)
59  {
60  boost::shared_lock<boost::shared_mutex> lock(*(mutex_.get()));
61 
62  typename InternalMap::iterator it = map_->find(first);
63  if (it != map_->end())
64  return it->second;
65  else
66  return T();
67  }
68 
69  bool insert(const std::string &first, const T &value)
70  {
71  if (!mutex_->timed_lock(boost::posix_time::microseconds(lock_wait_time)))
72  {
73  return false;
74  }
75 
76  keys_.push_back(first);
77  map_->insert(std::pair<std::string, T>(first, value));
78  mutex_->unlock();
79  return true;
80  }
81 
82  bool update(const std::string &first, const T &value)
83  {
84  if (!mutex_->timed_lock(boost::posix_time::microseconds(lock_wait_time)))
85  {
86  return false;
87  }
88 
89  (*map_)[first] = value;
90  mutex_->unlock();
91  return true;
92  }
93 
94  std::vector<std::string> keys()
95  {
96  return keys_;
97  }
98 
99 private:
100  static const int lock_wait_time = 100;
101 
102  typedef std::map<std::string, T> InternalMap;
103 
105 
107  std::vector<std::string> keys_;
108 };
109 } // namespace threadsafe
110 
111 /* For the emacs weenies in the crowd.
112 Local Variables:
113  c-basic-offset: 2
114 End:
115 */
116 
117 #endif
bool update(const std::string &first, const T &value)
std::vector< std::string > keys_
boost::shared_ptr< boost::shared_mutex > mutex_
std::map< std::string, T > InternalMap
std::vector< std::string > keys()
T find(std::string first)
bool insert(const std::string &first, const T &value)
static const int lock_wait_time
boost::shared_ptr< InternalMap > map_


sr_utilities
Author(s): Ugo Cupcic
autogenerated on Mon Feb 28 2022 23:52:19