Impossible to be const-correct when combining data and it's lock?
- by Graeme
I've been looking at ways to combine a piece of data which will be accessed by multiple threads alongside the lock provisioned for thread-safety. I think I've got to a point where I don't think its possible to do this whilst maintaining const-correctness.
Take the following class for example:
template <typename TType, typename TMutex>
class basic_lockable_type
{
public:
typedef TMutex lock_type;
public:
template <typename... TArgs>
explicit basic_lockable_type(TArgs&&... args)
: TType(std::forward<TArgs...>(args)...) {}
TType& data() { return data_; }
const TType& data() const { return data_; }
void lock() { mutex_.lock(); }
void unlock() { mutex_.unlock(); }
private:
TType data_;
mutable TMutex mutex_;
};
typedef basic_lockable_type<std::vector<int>, std::mutex> vector_with_lock;
In this I try to combine the data and lock, marking mutex_ as mutable. Unfortunately this isn't enough as I see it because when used, vector_with_lock would have to be marked as mutable in order for a read operation to be performed from a const function which isn't entirely correct (data_ should be mutable from a const).
void print_values() const
{
std::lock_guard<vector_with_lock>(values_);
for(const int val : values_)
{
std::cout << val << std::endl;
}
}
vector_with_lock values_;
Can anyone see anyway around this such that const-correctness is maintained whilst combining data and lock? Also, have I made any incorrect assumptions here?