Good day all,
Is there a logical way to lock data in an accessor?
Because accessors are generally declared as const methods and a lock() operation is not, how can you lock the class internally when the accessor is called?
For example:
When I implement GetValue(), i'd like to do:
But obviously this isn't good, since Lock/Unlock aren't const (and can't be).
I am sure I am not the first to try to make a class thread safe so I guess I'm just missing something...
Thanks!
EDIT: Strangely, I knew of a possible solution and yet it just disappeared from my head: using const_cast on the instance of the class (or lock) would be a valid solution. But would it be the best? What do you think?
Is there a logical way to lock data in an accessor?
Because accessors are generally declared as const methods and a lock() operation is not, how can you lock the class internally when the accessor is called?
For example:
Code:
class Class
{
public:
int GetValue() const;
protected:
void Lock();
void Unlock();
private:
int m_Value;
}
Code:
int Class::GetValue()
{
Lock();
int TmpValue = m_Value;
Unlock();
return(TmpValue);
}
I am sure I am not the first to try to make a class thread safe so I guess I'm just missing something...
Thanks!
EDIT: Strangely, I knew of a possible solution and yet it just disappeared from my head: using const_cast on the instance of the class (or lock) would be a valid solution. But would it be the best? What do you think?
Comment