One thread writes to the structure, other threads read. It is required to ensure the transactional nature of the record (i.e., so that when two fields are updated, the reading threads cannot be able to read half the updated data). Ideally, for reading, have the const Foo& get() const; method const Foo& get() const; .

The current implementation uses the mutex approach and storing separate copies for each stream in std :: map.

 void ConfigUpdater::set(const Config& config) { MutexGuard mutexGuard(mutex); this->config = config; } const Config& ConfigUpdater::get() const { MutexGuard mutexGuard(mutex); return copies.emplace(boost::this_thread::get_id(), config).first->second; } 

Perhaps there is a better solution, tell me which stronghold to dig.

  • Instead of a mutex, it is better to use spinlock - if you do not need synchronization between different processes, and if the write operation in the field is a trivial assignment, not copying megabytes. - gbg
  • one
    @gbg spinlock perhaps here really will be more pertinent, thanks. - Vladimir Gamalyan

2 answers 2

You can use std::shared_lock<std::shared_timed_mutex> to read and std::unique_lock<std::shared_timed_mutex> to write, this is to avoid copying. std::shared_timed_mutex is available in C ++ 14, in C ++ 17 there is std::shared_mutex .

  • std::shared_mutex looks almost perfect for my task (allows you to have read access at the same time without blocking). - Vladimir Gamalyan

If your structure is trivially replicable , wrap it in std::atomic<>

Each std :: atomic template specialization defines an atomic type. Only objects of atomic C ++ types can be safely used in several threads simultaneously. When one thread stores data in an atomic type object, and the other wants to read it, the program's behavior is defined by the standard.

 #include <atomic> //......... struct Foo { int alpha; char* beta; }; using AFoo=std::atomic<Foo>; 
  • Can an example be how to write / read Foo ? - Vladimir Gamalyan
  • @VladimirGamalian is naive - you distribute a link to it to threads, and they read. For the lock is responsible pattern. - gbg
  • 2
    I will not enter how it can work. Or is it just for each member of the structure separately that atomicity is guaranteed? Those. for example, in the reading stream, I first appeal to alpha , then to beta , how is it determined that this is a single transaction? - Vladimir Gamalyan
  • 2
    @VladimirGamalian and he will not give it to you, it will only allow you to get a copy of the structure as a whole. And he will do it atomically. And then he can also atomically completely rewrite the structure of the new structure. - gbg
  • Does std :: atomic guarantee that the memory view of all reading threads will be the same? - VladD