I have a class representing different kind of tools (GCC, LEX, YACC, …).
Each instance is given a type representing the tool, and permit special configuration.
To handle default configuration, I have a set of maps and vector storing defaults values. As I want that class to be usable in every context, it would have to be thread-safe, thus to avoid race I implemented the following:
int Tool::addType(std::string typeName,
std::string typeFlagName)
throw (GP::Exceptions::LockAcquisitionException)
{
static std::timed_mutex mutex;
std::unique_lock<std::timed_mutex> lock{mutex};
int typeId = 0;
if (lock.try_lock_for(std::chrono::microseconds(100)))
{
int typeId = typeNames.size();
typeNames[typeId] = typeName;
typeFlagNames[typeId] = typeFlagName;
}
else
{
throw GP::Exceptions::LockAcquisitionException{"Unable to generate new type ID within 100 microseconds."};
}
return typeId;
}
I would like to know if this is a good solution or if I miss something.
If this is okay, is there another solution less verbose?
Why not something like?
You could make this a bit smarter by using std::vector and have a lock only when it needs to be reallocated for a larger size.
NOTE: the throw() clause is deprecated in C++11.