Reputation: 4487
Lets consider such a class in C++:
class CuteClass
{
public:
int getFancyInt() const;
float getNiceFloat() const;
string getPerfectString() const;
void setIntSomething(int something);
void setInternalState(State newState);
};
The instance of this class could be accessed concurrently from several different threads. And then:
All getMethods (getFancyInt, getNiceFloat, getPerfectString) shouldn't block each other. They doesn't change the internal state of the object.
All setMethod (setIntSomething, setInternalState) should:
A simple lock_guard with mutex will met all requirements except one - getMethod would then block other getMethods.
What solution would be easy and clean in such scenario?
Upvotes: 5
Views: 824
Reputation: 8187
std::atomic
should resolve any concern about partly changed data.
[Edited:] No, it doesn't. If I don't delete this wrong answer it's only for the insightful comments that should be preserved.
Upvotes: 3
Reputation: 146
What you are loonking for is a R/W mutex.
You lock it as "READ" in all your getter and "WRITE" in all your setter.
Boost shared_mutex is what you are looking for
Example for boost shared_mutex (multiple reads/one write)?
In order to be compatible with your "const" declarations, you need to declare the mutex itself as mutable
Upvotes: 7