Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ set/get methods synchronization

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:

  • block each other - to avoid inconsistent state of object,
  • block all getMethods - to avoid returning partially changed data,
  • be blocked by all getMethods - to avoid returning partially changed data.

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?

like image 655
Dejwi Avatar asked Jan 07 '23 15:01

Dejwi


2 Answers

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

like image 131
adev Avatar answered Jan 15 '23 03:01

adev


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.

like image 31
Joachim W Avatar answered Jan 15 '23 05:01

Joachim W