thread_safe_map.hpp
Go to the documentation of this file.
00001 
00028 #ifndef _THREAD_SAFE_MAP_HPP_
00029 #define _THREAD_SAFE_MAP_HPP_
00030 
00031 #include <boost/smart_ptr.hpp>
00032 #include <boost/thread.hpp>
00033 
00034 #include <map>
00035 #include <vector>
00036 #include <iostream>
00037 
00038 namespace threadsafe
00039 {
00040   template <class T>
00041   class Map
00042   {
00043   public:
00044     Map()
00045     {
00046       mutex_ = boost::shared_ptr<boost::shared_mutex>(new boost::shared_mutex());
00047       map_ = boost::shared_ptr<InternalMap>(new InternalMap());
00048     };
00049     ~Map() {};
00050 
00051     T find(std::string first)
00052     {
00053       boost::shared_lock< boost::shared_mutex > lock( *(mutex_.get()) );
00054 
00055       return map_->find(first)->second;
00056     }
00057 
00058     bool insert(const std::string& first, const T& value)
00059     {
00060       if(!mutex_->timed_lock(boost::posix_time::microseconds(lock_wait_time)))
00061         return false;
00062 
00063       keys_.push_back(first);
00064       map_->insert(std::pair<std::string, T>(first, value));
00065       mutex_->unlock();
00066       return true;
00067     }
00068 
00069     bool update(const std::string& first, const T& value)
00070     {
00071       if(!mutex_->timed_lock(boost::posix_time::microseconds(lock_wait_time)))
00072         return false;
00073 
00074       (*map_)[first] = value;
00075       mutex_->unlock();
00076       return true;
00077 
00078     }
00079 
00080     std::vector<std::string> keys()
00081     {
00082       return keys_;
00083     }
00084 
00085   private:
00086     static const int lock_wait_time = 100;
00087 
00088     typedef std::map<std::string , T> InternalMap;
00089 
00090     boost::shared_ptr<InternalMap> map_;
00091 
00092     boost::shared_ptr<boost::shared_mutex> mutex_;
00093     std::vector<std::string> keys_;
00094   };
00095 }
00096 
00097 /* For the emacs weenies in the crowd.
00098 Local Variables:
00099    c-basic-offset: 2
00100 End:
00101 */
00102 
00103 #endif


sr_utilities
Author(s): Ugo Cupcic
autogenerated on Fri Aug 21 2015 12:24:47