Thread safety of feature vector.

git-svn-id: http://svn.statmt.org/repository/mira@3933 cc96ff50-19ce-11e0-b349-13d7f0bd23df
This commit is contained in:
bhaddow 2011-08-16 12:57:33 +00:00 committed by Ondrej Bojar
parent f19961c6a6
commit cc437739a1
2 changed files with 30 additions and 3 deletions

View File

@ -36,15 +36,34 @@ namespace Moses {
const string FName::SEP = "_";
FName::Name2Id FName::name2id;
vector<string> FName::id2name;
#ifdef WITH_THREADS
boost::shared_mutex FName::m_idLock;
#endif
void FName::init(const string& name) {
#ifdef WITH_THREADS
//reader lock
boost::shared_lock<boost::shared_mutex> lock(m_idLock);
#endif
Name2Id::iterator i = name2id.find(name);
if (i != name2id.end()) {
m_id = i->second;
} else {
m_id = name2id.size();
name2id[name] = m_id;
id2name.push_back(name);
#ifdef WITH_THREADS
//release the reader lock, and upgrade to writer lock
lock.unlock();
boost::upgrade_lock<boost::shared_mutex> upgradeLock(m_idLock);
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(upgradeLock);
#endif
//Need to check again if the id is in the map, as someone may have added
//it while we were waiting on the writer lock.
if (i != name2id.end()) {
m_id = i->second;
} else {
m_id = name2id.size();
name2id[name] = m_id;
id2name.push_back(name);
}
}
}

View File

@ -38,6 +38,10 @@
#include <boost/serialization/vector.hpp>
#endif
#ifdef WITH_THREADS
#include <boost/thread/shared_mutex.hpp>
#endif
namespace Moses {
typedef float FValue;
@ -73,6 +77,10 @@ namespace Moses {
private:
void init(const std::string& name);
size_t m_id;
#ifdef WITH_THREADS
//reader-writer lock
static boost::shared_mutex m_idLock;
#endif
};
std::ostream& operator<<(std::ostream& out,const FName& name);