thread_safe_map.hpp
Go to the documentation of this file.
1 
28 #ifndef _THREAD_SAFE_MAP_HPP_
29 #define _THREAD_SAFE_MAP_HPP_
30 
31 #include <boost/smart_ptr.hpp>
32 #include <boost/thread/shared_mutex.hpp>
33 #include <boost/thread/mutex.hpp>
34 
35 #include <map>
36 #include <vector>
37 #include <iostream>
38 #include <utility>
39 #include <string>
40 
41 namespace threadsafe
42 {
43 template<class T>
44 class Map
45 {
46 public:
47  Map()
48  {
49  mutex_ = boost::shared_ptr<boost::shared_mutex>(new boost::shared_mutex());
51  };
52 
53  ~Map()
54  {
55  };
56 
57  T find(std::string first)
58  {
59  boost::shared_lock<boost::shared_mutex> lock(*(mutex_.get()));
60 
61  typename InternalMap::iterator it = map_->find(first);
62  if (it != map_->end())
63  return it->second;
64  else
65  return T();
66  }
67 
68  bool insert(const std::string &first, const T &value)
69  {
70  if (!mutex_->timed_lock(boost::posix_time::microseconds(lock_wait_time)))
71  {
72  return false;
73  }
74 
75  keys_.push_back(first);
76  map_->insert(std::pair<std::string, T>(first, value));
77  mutex_->unlock();
78  return true;
79  }
80 
81  bool update(const std::string &first, const T &value)
82  {
83  if (!mutex_->timed_lock(boost::posix_time::microseconds(lock_wait_time)))
84  {
85  return false;
86  }
87 
88  (*map_)[first] = value;
89  mutex_->unlock();
90  return true;
91  }
92 
93  std::vector<std::string> keys()
94  {
95  return keys_;
96  }
97 
98 private:
99  static const int lock_wait_time = 100;
100 
101  typedef std::map<std::string, T> InternalMap;
102 
104 
106  std::vector<std::string> keys_;
107 };
108 } // namespace threadsafe
109 
110 /* For the emacs weenies in the crowd.
111 Local Variables:
112  c-basic-offset: 2
113 End:
114 */
115 
116 #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 Tue Oct 13 2020 03:55:49