FreeLing  4.0
safe_map.h
Go to the documentation of this file.
00001 
00002 //
00003 //    FreeLing - Open Source Language Analyzers
00004 //
00005 //    Copyright (C) 2014   TALP Research Center
00006 //                         Universitat Politecnica de Catalunya
00007 //
00008 //    This library is free software; you can redistribute it and/or
00009 //    modify it under the terms of the GNU Affero General Public
00010 //    License as published by the Free Software Foundation; either
00011 //    version 3 of the License, or (at your option) any later version.
00012 //
00013 //    This library is distributed in the hope that it will be useful,
00014 //    but WITHOUT ANY WARRANTY; without even the implied warranty of
00015 //    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016 //    Affero General Public License for more details.
00017 //
00018 //    You should have received a copy of the GNU Affero General Public
00019 //    License along with this library; if not, write to the Free Software
00020 //    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
00021 //
00022 //    contact: Lluis Padro (padro@lsi.upc.es)
00023 //             TALP Research Center
00024 //             despatx C6.212 - Campus Nord UPC
00025 //             08034 Barcelona.  SPAIN
00026 //
00028 
00029 #include <boost/thread/mutex.hpp>
00030 #include <iostream>
00031 
00035 
00036 #ifndef SAFEMAP_H
00037 #define SAFEMAP_H
00038 
00039 template <class T1, class T2> 
00040   class safe_map : public std::map<T1,T2> {
00041 
00042  private:
00043     boost::mutex sem;
00044 
00045  public:
00046     // check if key is in cache, if found, return true  
00047     // and set value in second parameter
00048     bool find_safe(const T1 &key, T2 &val) {
00049       bool b=false;
00050       sem.lock();
00051       typename std::map<T1,T2>::const_iterator p=this->find(key);
00052       if (p!=this->end()) {
00053         b = true;
00054         val = p->second;
00055       }
00056       sem.unlock();
00057       return b;
00058     }
00059 
00060     // insert new pair in cache, with mutex.
00061     void insert_safe(const T1 &key, const T2 &val) {
00062       sem.lock();
00063       this->insert(make_pair(key,val));
00064       sem.unlock();
00065     }
00066 
00067     // remove pair from cache, with mutex.
00068     void erase_safe(const T1 &key) {
00069       sem.lock();
00070       this->erase(key);
00071       sem.unlock();
00072     }
00073 };
00074 
00075 
00076 #endif